ExecutionTest.cpp 394 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // ExecutionTest.cpp //
  4. // Copyright (C) Microsoft Corporation. All rights reserved. //
  5. // This file is distributed under the University of Illinois Open Source //
  6. // License. See LICENSE.TXT for details. //
  7. // //
  8. // These tests run by executing compiled programs, and thus involve more //
  9. // moving parts, like the runtime and drivers. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. // We need to keep & fix these warnings to integrate smoothly with HLK
  13. #pragma warning(error: 4100 4146 4242 4244 4267 4701 4389)
  14. #include <algorithm>
  15. #include <memory>
  16. #include <array>
  17. #include <vector>
  18. #include <string>
  19. #include <map>
  20. #include <unordered_set>
  21. #include <strstream>
  22. #include <iomanip>
  23. #include "dxc/Test/CompilationResult.h"
  24. #include "dxc/Test/HLSLTestData.h"
  25. #include <Shlwapi.h>
  26. #include <atlcoll.h>
  27. #include <locale>
  28. #include <algorithm>
  29. #undef _read
  30. #include "WexTestClass.h"
  31. #include "dxc/Test/HlslTestUtils.h"
  32. #include "dxc/Test/DxcTestUtils.h"
  33. #include "dxc/Support/Global.h"
  34. #include "dxc/Support/WinIncludes.h"
  35. #include "dxc/Support/FileIOHelper.h"
  36. #include "dxc/Support/Unicode.h"
  37. //
  38. // d3d12.h and dxgi1_4.h are included in the Windows 10 SDK
  39. // https://msdn.microsoft.com/en-us/library/windows/desktop/dn899120(v=vs.85).aspx
  40. // https://developer.microsoft.com/en-US/windows/downloads/windows-10-sdk
  41. //
  42. #include <d3d12.h>
  43. #include <dxgi1_4.h>
  44. #include <DXGIDebug.h>
  45. #include "dxc/Support/d3dx12.h"
  46. #include <DirectXMath.h>
  47. #include <strsafe.h>
  48. #include <d3dcompiler.h>
  49. #include <wincodec.h>
  50. #include "ShaderOpTest.h"
  51. #pragma comment(lib, "d3dcompiler.lib")
  52. #pragma comment(lib, "windowscodecs.lib")
  53. #pragma comment(lib, "dxguid.lib")
  54. #pragma comment(lib, "version.lib")
  55. // A more recent Windows SDK than currently required is needed for these.
  56. typedef HRESULT(WINAPI *D3D12EnableExperimentalFeaturesFn)(
  57. UINT NumFeatures,
  58. __in_ecount(NumFeatures) const IID* pIIDs,
  59. __in_ecount_opt(NumFeatures) void* pConfigurationStructs,
  60. __in_ecount_opt(NumFeatures) UINT* pConfigurationStructSizes);
  61. static const GUID D3D12ExperimentalShaderModelsID = { /* 76f5573e-f13a-40f5-b297-81ce9e18933f */
  62. 0x76f5573e,
  63. 0xf13a,
  64. 0x40f5,
  65. { 0xb2, 0x97, 0x81, 0xce, 0x9e, 0x18, 0x93, 0x3f }
  66. };
  67. using namespace DirectX;
  68. using namespace hlsl_test;
  69. template <typename TSequence, typename T>
  70. static bool contains(TSequence s, const T &val) {
  71. return std::cend(s) != std::find(std::cbegin(s), std::cend(s), val);
  72. }
  73. template <typename InputIterator, typename T>
  74. static bool contains(InputIterator b, InputIterator e, const T &val) {
  75. return e != std::find(b, e, val);
  76. }
  77. static HRESULT ReportLiveObjects() {
  78. CComPtr<IDXGIDebug1> pDebug;
  79. IFR(DXGIGetDebugInterface1(0, IID_PPV_ARGS(&pDebug)));
  80. IFR(pDebug->ReportLiveObjects(DXGI_DEBUG_ALL, DXGI_DEBUG_RLO_ALL));
  81. return S_OK;
  82. }
  83. static void WriteInfoQueueMessages(void *pStrCtx, st::OutputStringFn pOutputStrFn, ID3D12InfoQueue *pInfoQueue) {
  84. bool allMessagesOK = true;
  85. UINT64 count = pInfoQueue->GetNumStoredMessages();
  86. CAtlArray<BYTE> message;
  87. for (UINT64 i = 0; i < count; ++i) {
  88. // 'GetMessageA' rather than 'GetMessage' is an artifact of user32 headers.
  89. SIZE_T msgLen = 0;
  90. if (FAILED(pInfoQueue->GetMessageA(i, nullptr, &msgLen))) {
  91. allMessagesOK = false;
  92. continue;
  93. }
  94. if (message.GetCount() < msgLen) {
  95. if (!message.SetCount(msgLen)) {
  96. allMessagesOK = false;
  97. continue;
  98. }
  99. }
  100. D3D12_MESSAGE *pMessage = (D3D12_MESSAGE *)message.GetData();
  101. if (FAILED(pInfoQueue->GetMessageA(i, pMessage, &msgLen))) {
  102. allMessagesOK = false;
  103. continue;
  104. }
  105. CA2W msgW(pMessage->pDescription, CP_ACP);
  106. pOutputStrFn(pStrCtx, msgW.m_psz);
  107. pOutputStrFn(pStrCtx, L"\r\n");
  108. }
  109. if (!allMessagesOK) {
  110. pOutputStrFn(pStrCtx, L"Failed to retrieve some messages.\r\n");
  111. }
  112. }
  113. class CComContext {
  114. private:
  115. bool m_init;
  116. public:
  117. CComContext() : m_init(false) {}
  118. ~CComContext() { Dispose(); }
  119. void Dispose() { if (!m_init) return; m_init = false; CoUninitialize(); }
  120. HRESULT Init() { HRESULT hr = CoInitializeEx(0, COINIT_MULTITHREADED); if (SUCCEEDED(hr)) { m_init = true; } return hr; }
  121. };
  122. static void SavePixelsToFile(LPCVOID pPixels, DXGI_FORMAT format, UINT32 m_width, UINT32 m_height, LPCWSTR pFileName) {
  123. CComContext ctx;
  124. CComPtr<IWICImagingFactory> pFactory;
  125. CComPtr<IWICBitmap> pBitmap;
  126. CComPtr<IWICBitmapEncoder> pEncoder;
  127. CComPtr<IWICBitmapFrameEncode> pFrameEncode;
  128. CComPtr<hlsl::AbstractMemoryStream> pStream;
  129. CComPtr<IMalloc> pMalloc;
  130. struct PF {
  131. DXGI_FORMAT Format;
  132. GUID PixelFormat;
  133. UINT32 PixelSize;
  134. bool operator==(DXGI_FORMAT F) const {
  135. return F == Format;
  136. }
  137. } Vals[] = {
  138. // Add more pixel format mappings as needed.
  139. { DXGI_FORMAT_R8G8B8A8_UNORM, GUID_WICPixelFormat32bppRGBA, 4 }
  140. };
  141. PF *pFormat = std::find(Vals, Vals + _countof(Vals), format);
  142. VERIFY_SUCCEEDED(ctx.Init());
  143. VERIFY_SUCCEEDED(CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_IWICImagingFactory, (LPVOID*)&pFactory));
  144. VERIFY_SUCCEEDED(CoGetMalloc(1, &pMalloc));
  145. VERIFY_SUCCEEDED(hlsl::CreateMemoryStream(pMalloc, &pStream));
  146. VERIFY_ARE_NOT_EQUAL(pFormat, Vals + _countof(Vals));
  147. VERIFY_SUCCEEDED(pFactory->CreateBitmapFromMemory(m_width, m_height, pFormat->PixelFormat, m_width * pFormat->PixelSize, m_width * m_height * pFormat->PixelSize, (BYTE *)pPixels, &pBitmap));
  148. VERIFY_SUCCEEDED(pFactory->CreateEncoder(GUID_ContainerFormatBmp, nullptr, &pEncoder));
  149. VERIFY_SUCCEEDED(pEncoder->Initialize(pStream, WICBitmapEncoderNoCache));
  150. VERIFY_SUCCEEDED(pEncoder->CreateNewFrame(&pFrameEncode, nullptr));
  151. VERIFY_SUCCEEDED(pFrameEncode->Initialize(nullptr));
  152. VERIFY_SUCCEEDED(pFrameEncode->WriteSource(pBitmap, nullptr));
  153. VERIFY_SUCCEEDED(pFrameEncode->Commit());
  154. VERIFY_SUCCEEDED(pEncoder->Commit());
  155. hlsl::WriteBinaryFile(pFileName, pStream->GetPtr(), pStream->GetPtrSize());
  156. }
  157. // Checks if the given warp version supports the given operation.
  158. bool IsValidWarpDllVersion(unsigned int minBuildNumber) {
  159. HMODULE pLibrary = LoadLibrary("D3D10Warp.dll");
  160. if (pLibrary) {
  161. char path[MAX_PATH];
  162. DWORD length = GetModuleFileName(pLibrary, path, MAX_PATH);
  163. if (length) {
  164. DWORD dwVerHnd = 0;
  165. DWORD dwVersionInfoSize = GetFileVersionInfoSize(path, &dwVerHnd);
  166. std::unique_ptr<int[]> VffInfo(new int[dwVersionInfoSize]);
  167. if (GetFileVersionInfo(path, NULL, dwVersionInfoSize, VffInfo.get())) {
  168. LPVOID versionInfo;
  169. UINT size;
  170. if (VerQueryValue(VffInfo.get(), "\\", &versionInfo, &size)) {
  171. if (size) {
  172. VS_FIXEDFILEINFO *verInfo = (VS_FIXEDFILEINFO *)versionInfo;
  173. unsigned int warpBuildNumber = verInfo->dwFileVersionLS >> 16 & 0xffff;
  174. if (verInfo->dwSignature == 0xFEEF04BD && warpBuildNumber >= minBuildNumber) {
  175. return true;
  176. }
  177. }
  178. }
  179. }
  180. }
  181. FreeLibrary(pLibrary);
  182. }
  183. return false;
  184. }
  185. #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS2
  186. #define D3D12_FEATURE_D3D12_OPTIONS3 ((D3D12_FEATURE)21)
  187. #define NTDDI_WIN10_RS3 0x0A000004 /* ABRACADABRA_WIN10_RS2 */
  188. typedef
  189. enum D3D12_COMMAND_LIST_SUPPORT_FLAGS
  190. {
  191. D3D12_COMMAND_LIST_SUPPORT_FLAG_NONE = 0,
  192. D3D12_COMMAND_LIST_SUPPORT_FLAG_DIRECT = (1 << D3D12_COMMAND_LIST_TYPE_DIRECT),
  193. D3D12_COMMAND_LIST_SUPPORT_FLAG_BUNDLE = (1 << D3D12_COMMAND_LIST_TYPE_BUNDLE),
  194. D3D12_COMMAND_LIST_SUPPORT_FLAG_COMPUTE = (1 << D3D12_COMMAND_LIST_TYPE_COMPUTE),
  195. D3D12_COMMAND_LIST_SUPPORT_FLAG_COPY = (1 << D3D12_COMMAND_LIST_TYPE_COPY),
  196. D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_DECODE = (1 << 4),
  197. D3D12_COMMAND_LIST_SUPPORT_FLAG_VIDEO_PROCESS = (1 << 5)
  198. } D3D12_COMMAND_LIST_SUPPORT_FLAGS;
  199. typedef
  200. enum D3D12_VIEW_INSTANCING_TIER
  201. {
  202. D3D12_VIEW_INSTANCING_TIER_NOT_SUPPORTED = 0,
  203. D3D12_VIEW_INSTANCING_TIER_1 = 1,
  204. D3D12_VIEW_INSTANCING_TIER_2 = 2,
  205. D3D12_VIEW_INSTANCING_TIER_3 = 3
  206. } D3D12_VIEW_INSTANCING_TIER;
  207. typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS3
  208. {
  209. _Out_ BOOL CopyQueueTimestampQueriesSupported;
  210. _Out_ BOOL CastingFullyTypedFormatSupported;
  211. _Out_ DWORD WriteBufferImmediateSupportFlags;
  212. _Out_ D3D12_VIEW_INSTANCING_TIER ViewInstancingTier;
  213. _Out_ BOOL BarycentricsSupported;
  214. } D3D12_FEATURE_DATA_D3D12_OPTIONS3;
  215. #endif
  216. #if WDK_NTDDI_VERSION <= NTDDI_WIN10_RS3
  217. #define D3D12_FEATURE_D3D12_OPTIONS4 ((D3D12_FEATURE)23)
  218. typedef enum D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER
  219. {
  220. D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_0,
  221. D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER_1,
  222. } D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER;
  223. typedef struct D3D12_FEATURE_DATA_D3D12_OPTIONS4
  224. {
  225. _Out_ BOOL ReservedBufferPlacementSupported;
  226. _Out_ D3D12_SHARED_RESOURCE_COMPATIBILITY_TIER SharedResourceCompatibilityTier;
  227. _Out_ BOOL Native16BitShaderOpsSupported;
  228. } D3D12_FEATURE_DATA_D3D12_OPTIONS4;
  229. #endif
  230. // Virtual class to compute the expected result given a set of inputs
  231. struct TableParameter;
  232. class ExecutionTest {
  233. public:
  234. // By default, ignore these tests, which require a recent build to run properly.
  235. BEGIN_TEST_CLASS(ExecutionTest)
  236. TEST_CLASS_PROPERTY(L"Parallel", L"true")
  237. TEST_CLASS_PROPERTY(L"Ignore", L"true")
  238. TEST_METHOD_PROPERTY(L"Priority", L"0")
  239. END_TEST_CLASS()
  240. TEST_CLASS_SETUP(ExecutionTestClassSetup)
  241. TEST_METHOD(BasicComputeTest);
  242. TEST_METHOD(BasicTriangleTest);
  243. TEST_METHOD(BasicTriangleOpTest);
  244. TEST_METHOD(BasicTriangleOpTestHalf);
  245. TEST_METHOD(OutOfBoundsTest);
  246. TEST_METHOD(SaturateTest);
  247. TEST_METHOD(SignTest);
  248. TEST_METHOD(Int64Test);
  249. TEST_METHOD(LifetimeIntrinsicTest)
  250. TEST_METHOD(WaveIntrinsicsTest);
  251. TEST_METHOD(WaveIntrinsicsDDITest);
  252. TEST_METHOD(WaveIntrinsicsInPSTest);
  253. TEST_METHOD(WaveSizeTest);
  254. TEST_METHOD(PartialDerivTest);
  255. TEST_METHOD(DerivativesTest);
  256. TEST_METHOD(ComputeSampleTest);
  257. TEST_METHOD(AtomicsTest);
  258. TEST_METHOD(Atomics64Test);
  259. TEST_METHOD(AtomicsRawHeap64Test);
  260. TEST_METHOD(AtomicsTyped64Test);
  261. TEST_METHOD(AtomicsShared64Test);
  262. TEST_METHOD(AtomicsFloatTest);
  263. TEST_METHOD(HelperLaneTest);
  264. TEST_METHOD(HelperLaneTestWave);
  265. TEST_METHOD(SignatureResourcesTest)
  266. TEST_METHOD(DynamicResourcesTest)
  267. TEST_METHOD(QuadReadTest)
  268. TEST_METHOD(CBufferTestHalf);
  269. TEST_METHOD(BasicShaderModel61);
  270. TEST_METHOD(BasicShaderModel63);
  271. BEGIN_TEST_METHOD(WaveIntrinsicsActiveIntTest)
  272. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveIntTable")
  273. END_TEST_METHOD()
  274. BEGIN_TEST_METHOD(WaveIntrinsicsActiveUintTest)
  275. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsActiveUintTable")
  276. END_TEST_METHOD()
  277. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixIntTest)
  278. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixIntTable")
  279. END_TEST_METHOD()
  280. BEGIN_TEST_METHOD(WaveIntrinsicsPrefixUintTest)
  281. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsPrefixUintTable")
  282. END_TEST_METHOD()
  283. BEGIN_TEST_METHOD(WaveIntrinsicsSM65IntTest)
  284. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsMultiPrefixIntTable")
  285. END_TEST_METHOD()
  286. BEGIN_TEST_METHOD(WaveIntrinsicsSM65UintTest)
  287. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#WaveIntrinsicsMultiPrefixUintTable")
  288. END_TEST_METHOD()
  289. // TAEF data-driven tests.
  290. BEGIN_TEST_METHOD(UnaryFloatOpTest)
  291. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryFloatOpTable")
  292. END_TEST_METHOD()
  293. BEGIN_TEST_METHOD(BinaryFloatOpTest)
  294. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryFloatOpTable")
  295. END_TEST_METHOD()
  296. BEGIN_TEST_METHOD(TertiaryFloatOpTest)
  297. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryFloatOpTable")
  298. END_TEST_METHOD()
  299. BEGIN_TEST_METHOD(UnaryHalfOpTest)
  300. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryHalfOpTable")
  301. END_TEST_METHOD()
  302. BEGIN_TEST_METHOD(BinaryHalfOpTest)
  303. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryHalfOpTable")
  304. END_TEST_METHOD()
  305. BEGIN_TEST_METHOD(TertiaryHalfOpTest)
  306. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryHalfOpTable")
  307. END_TEST_METHOD()
  308. BEGIN_TEST_METHOD(UnaryIntOpTest)
  309. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryIntOpTable")
  310. END_TEST_METHOD()
  311. BEGIN_TEST_METHOD(BinaryIntOpTest)
  312. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryIntOpTable")
  313. END_TEST_METHOD()
  314. BEGIN_TEST_METHOD(TertiaryIntOpTest)
  315. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryIntOpTable")
  316. END_TEST_METHOD()
  317. BEGIN_TEST_METHOD(UnaryUintOpTest)
  318. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUintOpTable")
  319. END_TEST_METHOD()
  320. BEGIN_TEST_METHOD(BinaryUintOpTest)
  321. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUintOpTable")
  322. END_TEST_METHOD()
  323. BEGIN_TEST_METHOD(TertiaryUintOpTest)
  324. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUintOpTable")
  325. END_TEST_METHOD()
  326. BEGIN_TEST_METHOD(UnaryInt16OpTest)
  327. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryInt16OpTable")
  328. END_TEST_METHOD()
  329. BEGIN_TEST_METHOD(BinaryInt16OpTest)
  330. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryInt16OpTable")
  331. END_TEST_METHOD()
  332. BEGIN_TEST_METHOD(TertiaryInt16OpTest)
  333. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryInt16OpTable")
  334. END_TEST_METHOD()
  335. BEGIN_TEST_METHOD(UnaryUint16OpTest)
  336. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#UnaryUint16OpTable")
  337. END_TEST_METHOD()
  338. BEGIN_TEST_METHOD(BinaryUint16OpTest)
  339. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#BinaryUint16OpTable")
  340. END_TEST_METHOD()
  341. BEGIN_TEST_METHOD(TertiaryUint16OpTest)
  342. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#TertiaryUint16OpTable")
  343. END_TEST_METHOD()
  344. BEGIN_TEST_METHOD(DotTest)
  345. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DotOpTable")
  346. END_TEST_METHOD()
  347. BEGIN_TEST_METHOD(Dot2AddHalfTest)
  348. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot2AddHalfOpTable")
  349. END_TEST_METHOD()
  350. BEGIN_TEST_METHOD(Dot4AddI8PackedTest)
  351. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot4AddI8PackedOpTable")
  352. END_TEST_METHOD()
  353. BEGIN_TEST_METHOD(Dot4AddU8PackedTest)
  354. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Dot4AddU8PackedOpTable")
  355. END_TEST_METHOD()
  356. BEGIN_TEST_METHOD(Msad4Test)
  357. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#Msad4Table")
  358. END_TEST_METHOD()
  359. BEGIN_TEST_METHOD(DenormBinaryFloatOpTest)
  360. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DenormBinaryFloatOpTable")
  361. END_TEST_METHOD()
  362. BEGIN_TEST_METHOD(DenormTertiaryFloatOpTest)
  363. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#DenormTertiaryFloatOpTable")
  364. END_TEST_METHOD()
  365. TEST_METHOD(BarycentricsTest);
  366. TEST_METHOD(ComputeRawBufferLdStI32);
  367. TEST_METHOD(ComputeRawBufferLdStFloat);
  368. TEST_METHOD(ComputeRawBufferLdStI64);
  369. TEST_METHOD(ComputeRawBufferLdStDouble);
  370. TEST_METHOD(ComputeRawBufferLdStI16);
  371. TEST_METHOD(ComputeRawBufferLdStHalf);
  372. TEST_METHOD(GraphicsRawBufferLdStI32);
  373. TEST_METHOD(GraphicsRawBufferLdStFloat);
  374. TEST_METHOD(GraphicsRawBufferLdStI64);
  375. TEST_METHOD(GraphicsRawBufferLdStDouble);
  376. TEST_METHOD(GraphicsRawBufferLdStI16);
  377. TEST_METHOD(GraphicsRawBufferLdStHalf);
  378. BEGIN_TEST_METHOD(PackUnpackTest)
  379. TEST_METHOD_PROPERTY(L"DataSource", L"Table:ShaderOpArithTable.xml#PackUnpackOpTable")
  380. END_TEST_METHOD()
  381. dxc::DxcDllSupport m_support;
  382. VersionSupportInfo m_ver;
  383. bool m_ExperimentalModeEnabled = false;
  384. const float ClearColor[4] = { 0.0f, 0.2f, 0.4f, 1.0f };
  385. bool DivergentClassSetup() {
  386. HRESULT hr;
  387. hr = EnableExperimentalMode();
  388. if (FAILED(hr)) {
  389. LogCommentFmt(L"Unable to enable shader experimental mode - 0x%08x.", hr);
  390. } else if (hr == S_FALSE) {
  391. LogCommentFmt(L"Experimental mode not enabled.");
  392. } else {
  393. LogCommentFmt(L"Experimental mode enabled.");
  394. }
  395. hr = EnableDebugLayer();
  396. if (FAILED(hr)) {
  397. LogCommentFmt(L"Unable to enable debug layer - 0x%08x.", hr);
  398. } else if (hr == S_FALSE) {
  399. LogCommentFmt(L"Debug layer not enabled.");
  400. } else {
  401. LogCommentFmt(L"Debug layer enabled.");
  402. }
  403. return true;
  404. }
  405. // Do not remove the following line - it is used by TranslateExecutionTest.py
  406. // MARKER: ExecutionTest/DxilConf Shared Implementation Start
  407. // This is defined in d3d.h for Windows 10 Anniversary Edition SDK, but we only
  408. // require the Windows 10 SDK.
  409. typedef enum D3D_SHADER_MODEL {
  410. D3D_SHADER_MODEL_5_1 = 0x51,
  411. D3D_SHADER_MODEL_6_0 = 0x60,
  412. D3D_SHADER_MODEL_6_1 = 0x61,
  413. D3D_SHADER_MODEL_6_2 = 0x62,
  414. D3D_SHADER_MODEL_6_3 = 0x63,
  415. D3D_SHADER_MODEL_6_4 = 0x64,
  416. D3D_SHADER_MODEL_6_5 = 0x65,
  417. D3D_SHADER_MODEL_6_6 = 0x66,
  418. } D3D_SHADER_MODEL;
  419. #if WDK_NTDDI_VERSION == NTDDI_WIN10_RS2
  420. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_0;
  421. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS3
  422. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_1;
  423. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS4
  424. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_2;
  425. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_RS5
  426. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_3;
  427. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_19H1
  428. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_4;
  429. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_VB
  430. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_5;
  431. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_MN
  432. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_5;
  433. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_FE
  434. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  435. #elif WDK_NTDDI_VERSION == NTDDI_WIN10_CO
  436. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  437. #else
  438. static const D3D_SHADER_MODEL HIGHEST_SHADER_MODEL = D3D_SHADER_MODEL_6_6;
  439. #endif
  440. bool UseDxbc() {
  441. #ifdef _HLK_CONF
  442. return false;
  443. #else
  444. return GetTestParamBool(L"DXBC");
  445. #endif
  446. }
  447. bool UseWarpByDefault() {
  448. #ifdef _HLK_CONF
  449. return false;
  450. #else
  451. return true;
  452. #endif
  453. }
  454. bool UseDebugIfaces() {
  455. return true;
  456. }
  457. bool SaveImages() {
  458. return GetTestParamBool(L"SaveImages");
  459. }
  460. void RunResourceTest(ID3D12Device *pDevice, const char *pShader, const wchar_t *sm, bool isDynamic);
  461. template <class T1, class T2>
  462. void WaveIntrinsicsActivePrefixTest(TableParameter *pParameterList,
  463. size_t numParameter, bool isPrefix);
  464. template <typename T>
  465. void WaveIntrinsicsMultiPrefixOpTest(TableParameter *pParameterList,
  466. size_t numParameters);
  467. void BasicTriangleTestSetup(LPCSTR OpName, LPCWSTR FileName, D3D_SHADER_MODEL testModel);
  468. void RunBasicShaderModelTest(D3D_SHADER_MODEL shaderModel);
  469. enum class RawBufferLdStType {
  470. I32,
  471. Float,
  472. I64,
  473. Double,
  474. I16,
  475. Half
  476. };
  477. template <class Ty>
  478. struct RawBufferLdStTestData {
  479. Ty v1, v2[2], v3[3], v4[4];
  480. };
  481. template <class Ty>
  482. struct RawBufferLdStUavData {
  483. RawBufferLdStTestData<Ty> input, output, srvOut;
  484. };
  485. template <class Ty>
  486. void RunComputeRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  487. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData);
  488. template <class Ty>
  489. void RunGraphicsRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  490. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData);
  491. template <class Ty>
  492. void VerifyRawBufferLdStTestResults(const std::shared_ptr<st::ShaderOpTest> test, const RawBufferLdStTestData<Ty> &testData);
  493. bool SetupRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType, CComPtr<ID3D12Device> &pDevice,
  494. CComPtr<IStream> &pStream, char *&sTy, char *&additionalOptions);
  495. template <class Ty>
  496. void RunBasicShaderModelTest(CComPtr<ID3D12Device> pDevice, const char *pShaderModelStr, const char *pShader, Ty *pInputDataPairs, unsigned inputDataCount);
  497. template <class Ty>
  498. const wchar_t* BasicShaderModelTest_GetFormatString();
  499. void CompileFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob, LPCWSTR *pOptions = nullptr, int numOptions = 0) {
  500. VERIFY_SUCCEEDED(m_support.Initialize());
  501. CComPtr<IDxcCompiler> pCompiler;
  502. CComPtr<IDxcLibrary> pLibrary;
  503. CComPtr<IDxcBlobEncoding> pTextBlob;
  504. CComPtr<IDxcOperationResult> pResult;
  505. HRESULT resultCode;
  506. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcCompiler, &pCompiler));
  507. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  508. VERIFY_SUCCEEDED(pLibrary->CreateBlobWithEncodingFromPinned(pText, (UINT32)strlen(pText), CP_UTF8, &pTextBlob));
  509. VERIFY_SUCCEEDED(pCompiler->Compile(pTextBlob, L"hlsl.hlsl", pEntryPoint, pTargetProfile, pOptions, numOptions, nullptr, 0, nullptr, &pResult));
  510. VERIFY_SUCCEEDED(pResult->GetStatus(&resultCode));
  511. if (FAILED(resultCode)) {
  512. CComPtr<IDxcBlobEncoding> errors;
  513. VERIFY_SUCCEEDED(pResult->GetErrorBuffer(&errors));
  514. #ifndef _HLK_CONF
  515. LogCommentFmt(L"Failed to compile shader: %s", BlobToUtf16(errors).data());
  516. #endif
  517. }
  518. VERIFY_SUCCEEDED(resultCode);
  519. VERIFY_SUCCEEDED(pResult->GetResult((IDxcBlob **)ppBlob));
  520. }
  521. void CreateCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue, D3D12_COMMAND_LIST_TYPE type) {
  522. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  523. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  524. queueDesc.Type = type;
  525. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  526. VERIFY_SUCCEEDED((*ppCommandQueue)->SetName(pName));
  527. }
  528. void CreateComputeCommandQueue(ID3D12Device *pDevice, LPCWSTR pName, ID3D12CommandQueue **ppCommandQueue) {
  529. CreateCommandQueue(pDevice, pName, ppCommandQueue, D3D12_COMMAND_LIST_TYPE_COMPUTE);
  530. }
  531. void CreateComputePSO(ID3D12Device *pDevice, ID3D12RootSignature *pRootSignature, LPCSTR pShader, LPCWSTR pTargetProfile, ID3D12PipelineState **ppComputeState, LPCWSTR *pOptions = nullptr, int numOptions = 0) {
  532. CComPtr<ID3DBlob> pComputeShader;
  533. // Load and compile shaders.
  534. if (UseDxbc()) {
  535. #ifndef _HLK_CONF
  536. DXBCFromText(pShader, L"main", pTargetProfile, &pComputeShader);
  537. #endif
  538. }
  539. else {
  540. CompileFromText(pShader, L"main", pTargetProfile, &pComputeShader, pOptions, numOptions);
  541. }
  542. // Describe and create the compute pipeline state object (PSO).
  543. D3D12_COMPUTE_PIPELINE_STATE_DESC computePsoDesc = {};
  544. computePsoDesc.pRootSignature = pRootSignature;
  545. computePsoDesc.CS = CD3DX12_SHADER_BYTECODE(pComputeShader);
  546. VERIFY_SUCCEEDED(pDevice->CreateComputePipelineState(&computePsoDesc, IID_PPV_ARGS(ppComputeState)));
  547. }
  548. bool CreateDevice(_COM_Outptr_ ID3D12Device **ppDevice,
  549. D3D_SHADER_MODEL testModel = D3D_SHADER_MODEL_6_0, bool skipUnsupported = true) {
  550. if (testModel > HIGHEST_SHADER_MODEL) {
  551. UINT minor = (UINT)testModel & 0x0f;
  552. LogCommentFmt(L"Installed SDK does not support "
  553. L"shader model 6.%1u", minor);
  554. if (skipUnsupported) {
  555. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  556. }
  557. return false;
  558. }
  559. CComPtr<IDXGIFactory4> factory;
  560. CComPtr<ID3D12Device> pDevice;
  561. *ppDevice = nullptr;
  562. VERIFY_SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
  563. if (GetTestParamUseWARP(UseWarpByDefault())) {
  564. CComPtr<IDXGIAdapter> warpAdapter;
  565. VERIFY_SUCCEEDED(factory->EnumWarpAdapter(IID_PPV_ARGS(&warpAdapter)));
  566. HRESULT createHR = D3D12CreateDevice(warpAdapter, D3D_FEATURE_LEVEL_11_0,
  567. IID_PPV_ARGS(&pDevice));
  568. if (FAILED(createHR)) {
  569. LogCommentFmt(L"The available version of WARP does not support d3d12.");
  570. if (skipUnsupported) {
  571. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  572. }
  573. return false;
  574. }
  575. } else {
  576. CComPtr<IDXGIAdapter1> hardwareAdapter;
  577. WEX::Common::String AdapterValue;
  578. HRESULT hr = WEX::TestExecution::RuntimeParameters::TryGetValue(L"Adapter",
  579. AdapterValue);
  580. if (SUCCEEDED(hr)) {
  581. GetHardwareAdapter(factory, AdapterValue, &hardwareAdapter);
  582. } else {
  583. WEX::Logging::Log::Comment(
  584. L"Using default hardware adapter with D3D12 support.");
  585. }
  586. VERIFY_SUCCEEDED(D3D12CreateDevice(hardwareAdapter, D3D_FEATURE_LEVEL_11_0,
  587. IID_PPV_ARGS(&pDevice)));
  588. }
  589. // retrieve adapter information
  590. LUID adapterID = pDevice->GetAdapterLuid();
  591. CComPtr<IDXGIAdapter> adapter;
  592. factory->EnumAdapterByLuid(adapterID, IID_PPV_ARGS(&adapter));
  593. DXGI_ADAPTER_DESC AdapterDesc;
  594. VERIFY_SUCCEEDED(adapter->GetDesc(&AdapterDesc));
  595. LogCommentFmt(L"Using Adapter:%s", AdapterDesc.Description);
  596. if (pDevice == nullptr)
  597. return false;
  598. if (!UseDxbc()) {
  599. // Check for DXIL support.
  600. typedef struct D3D12_FEATURE_DATA_SHADER_MODEL {
  601. _Inout_ D3D_SHADER_MODEL HighestShaderModel;
  602. } D3D12_FEATURE_DATA_SHADER_MODEL;
  603. const UINT D3D12_FEATURE_SHADER_MODEL = 7;
  604. D3D12_FEATURE_DATA_SHADER_MODEL SMData;
  605. SMData.HighestShaderModel = testModel;
  606. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_SHADER_MODEL,
  607. &SMData, sizeof(SMData))) ||
  608. SMData.HighestShaderModel < testModel) {
  609. UINT minor = (UINT)testModel & 0x0f;
  610. LogCommentFmt(L"The selected device does not support "
  611. L"shader model 6.%1u", minor);
  612. if (skipUnsupported) {
  613. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  614. }
  615. return false;
  616. }
  617. }
  618. if (UseDebugIfaces()) {
  619. CComPtr<ID3D12InfoQueue> pInfoQueue;
  620. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  621. pInfoQueue->SetMuteDebugOutput(FALSE);
  622. }
  623. }
  624. *ppDevice = pDevice.Detach();
  625. return true;
  626. }
  627. void CreateGraphicsCommandQueue(ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue) {
  628. D3D12_COMMAND_QUEUE_DESC queueDesc = {};
  629. queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
  630. queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;;
  631. VERIFY_SUCCEEDED(pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(ppCommandQueue)));
  632. }
  633. void CreateGraphicsCommandQueueAndList(
  634. ID3D12Device *pDevice, ID3D12CommandQueue **ppCommandQueue,
  635. ID3D12CommandAllocator **ppAllocator,
  636. ID3D12GraphicsCommandList **ppCommandList, ID3D12PipelineState *pPSO) {
  637. CreateGraphicsCommandQueue(pDevice, ppCommandQueue);
  638. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(
  639. D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(ppAllocator)));
  640. VERIFY_SUCCEEDED(pDevice->CreateCommandList(
  641. 0, D3D12_COMMAND_LIST_TYPE_DIRECT, *ppAllocator, pPSO,
  642. IID_PPV_ARGS(ppCommandList)));
  643. }
  644. void CreateGraphicsPSO(ID3D12Device *pDevice,
  645. D3D12_INPUT_LAYOUT_DESC *pInputLayout,
  646. ID3D12RootSignature *pRootSignature, LPCSTR pShaders,
  647. ID3D12PipelineState **ppPSO) {
  648. CComPtr<ID3DBlob> vertexShader;
  649. CComPtr<ID3DBlob> pixelShader;
  650. if (UseDxbc()) {
  651. #ifndef _HLK_CONF
  652. DXBCFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  653. DXBCFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  654. #endif
  655. } else {
  656. CompileFromText(pShaders, L"VSMain", L"vs_6_0", &vertexShader);
  657. CompileFromText(pShaders, L"PSMain", L"ps_6_0", &pixelShader);
  658. }
  659. // Describe and create the graphics pipeline state object (PSO).
  660. D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc = {};
  661. psoDesc.InputLayout = *pInputLayout;
  662. psoDesc.pRootSignature = pRootSignature;
  663. psoDesc.VS = CD3DX12_SHADER_BYTECODE(vertexShader);
  664. psoDesc.PS = CD3DX12_SHADER_BYTECODE(pixelShader);
  665. psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
  666. psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
  667. psoDesc.DepthStencilState.DepthEnable = FALSE;
  668. psoDesc.DepthStencilState.StencilEnable = FALSE;
  669. psoDesc.SampleMask = UINT_MAX;
  670. psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
  671. psoDesc.NumRenderTargets = 1;
  672. psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
  673. psoDesc.SampleDesc.Count = 1;
  674. VERIFY_SUCCEEDED(
  675. pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(ppPSO)));
  676. }
  677. void CreateRenderTargetAndReadback(ID3D12Device *pDevice,
  678. ID3D12DescriptorHeap *pHeap, UINT width,
  679. UINT height,
  680. ID3D12Resource **ppRenderTarget,
  681. ID3D12Resource **ppBuffer) {
  682. const DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
  683. const size_t formatElementSize = 4;
  684. CComPtr<ID3D12Resource> pRenderTarget;
  685. CComPtr<ID3D12Resource> pBuffer;
  686. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(
  687. pHeap->GetCPUDescriptorHandleForHeapStart());
  688. CD3DX12_HEAP_PROPERTIES rtHeap(D3D12_HEAP_TYPE_DEFAULT);
  689. CD3DX12_RESOURCE_DESC rtDesc(
  690. CD3DX12_RESOURCE_DESC::Tex2D(format, width, height));
  691. CD3DX12_CLEAR_VALUE rtClearVal(format, ClearColor);
  692. rtDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET;
  693. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  694. &rtHeap, D3D12_HEAP_FLAG_NONE, &rtDesc, D3D12_RESOURCE_STATE_COPY_DEST,
  695. &rtClearVal, IID_PPV_ARGS(&pRenderTarget)));
  696. pDevice->CreateRenderTargetView(pRenderTarget, nullptr, rtvHandle);
  697. // rtvHandle.Offset(1, rtvDescriptorSize); // Not needed for a single
  698. // resource.
  699. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  700. CD3DX12_RESOURCE_DESC readDesc(
  701. CD3DX12_RESOURCE_DESC::Buffer(width * height * formatElementSize));
  702. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  703. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  704. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pBuffer)));
  705. *ppRenderTarget = pRenderTarget.Detach();
  706. *ppBuffer = pBuffer.Detach();
  707. }
  708. void CreateRootSignatureFromDesc(ID3D12Device *pDevice,
  709. const D3D12_ROOT_SIGNATURE_DESC *pDesc,
  710. ID3D12RootSignature **pRootSig) {
  711. CComPtr<ID3DBlob> signature;
  712. CComPtr<ID3DBlob> error;
  713. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(pDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  714. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(
  715. 0, signature->GetBufferPointer(), signature->GetBufferSize(),
  716. IID_PPV_ARGS(pRootSig)));
  717. }
  718. void CreateRootSignatureFromRanges(ID3D12Device *pDevice, ID3D12RootSignature **pRootSig,
  719. CD3DX12_DESCRIPTOR_RANGE *resRanges, UINT resCt,
  720. CD3DX12_DESCRIPTOR_RANGE *sampRanges = nullptr, UINT sampCt = 0,
  721. D3D12_ROOT_SIGNATURE_FLAGS flags = D3D12_ROOT_SIGNATURE_FLAG_NONE) {
  722. CD3DX12_ROOT_PARAMETER rootParameters[2];
  723. rootParameters[0].InitAsDescriptorTable(resCt, resRanges, D3D12_SHADER_VISIBILITY_ALL);
  724. rootParameters[1].InitAsDescriptorTable(sampCt, sampRanges, D3D12_SHADER_VISIBILITY_ALL);
  725. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  726. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, flags);
  727. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, pRootSig);
  728. }
  729. void CreateRtvDescriptorHeap(ID3D12Device *pDevice, UINT numDescriptors,
  730. ID3D12DescriptorHeap **pRtvHeap, UINT *rtvDescriptorSize) {
  731. D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
  732. rtvHeapDesc.NumDescriptors = numDescriptors;
  733. rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
  734. rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
  735. VERIFY_SUCCEEDED(
  736. pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(pRtvHeap)));
  737. if (rtvDescriptorSize != nullptr) {
  738. *rtvDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(
  739. D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
  740. }
  741. }
  742. void CreateTestResources(ID3D12Device *pDevice,
  743. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  744. UINT32 valueSizeInBytes, D3D12_RESOURCE_DESC resDesc,
  745. ID3D12Resource **ppResource,
  746. ID3D12Resource **ppUploadResource,
  747. ID3D12Resource **ppReadBuffer = nullptr) {
  748. CComPtr<ID3D12Resource> pResource;
  749. CComPtr<ID3D12Resource> pReadBuffer;
  750. CComPtr<ID3D12Resource> pUploadResource;
  751. D3D12_SUBRESOURCE_DATA transferData;
  752. D3D12_HEAP_PROPERTIES defaultHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT);
  753. D3D12_HEAP_PROPERTIES uploadHeapProperties = CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD);
  754. D3D12_RESOURCE_DESC uploadBufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  755. CD3DX12_HEAP_PROPERTIES readHeap(D3D12_HEAP_TYPE_READBACK);
  756. CD3DX12_RESOURCE_DESC readDesc(CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes));
  757. pDevice->GetCopyableFootprints(&resDesc, 0, 1/*mipleveles*/, 0, nullptr, nullptr, nullptr, &uploadBufferDesc.Width);
  758. uploadBufferDesc.Height = 1;
  759. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  760. &defaultHeapProperties,
  761. D3D12_HEAP_FLAG_NONE,
  762. &resDesc,
  763. D3D12_RESOURCE_STATE_COPY_DEST,
  764. nullptr,
  765. IID_PPV_ARGS(&pResource)));
  766. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  767. &uploadHeapProperties,
  768. D3D12_HEAP_FLAG_NONE,
  769. &uploadBufferDesc,
  770. D3D12_RESOURCE_STATE_GENERIC_READ,
  771. nullptr,
  772. IID_PPV_ARGS(&pUploadResource)));
  773. if (ppReadBuffer)
  774. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  775. &readHeap, D3D12_HEAP_FLAG_NONE, &readDesc,
  776. D3D12_RESOURCE_STATE_COPY_DEST, nullptr, IID_PPV_ARGS(&pReadBuffer)));
  777. transferData.pData = values;
  778. transferData.RowPitch = valueSizeInBytes/resDesc.Height;
  779. transferData.SlicePitch = valueSizeInBytes;
  780. UpdateSubresources<1>(pCommandList, pResource.p, pUploadResource.p, 0, 0, 1, &transferData);
  781. if (resDesc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)
  782. RecordTransitionBarrier(pCommandList, pResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_UNORDERED_ACCESS);
  783. else
  784. RecordTransitionBarrier(pCommandList, pResource, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COMMON);
  785. *ppResource = pResource.Detach();
  786. *ppUploadResource = pUploadResource.Detach();
  787. if (ppReadBuffer)
  788. *ppReadBuffer = pReadBuffer.Detach();
  789. }
  790. void CreateTestUavs(ID3D12Device *pDevice,
  791. ID3D12GraphicsCommandList *pCommandList, LPCVOID values,
  792. UINT32 valueSizeInBytes, ID3D12Resource **ppUavResource,
  793. ID3D12Resource **ppUploadResource = nullptr,
  794. ID3D12Resource **ppReadBuffer = nullptr) {
  795. D3D12_RESOURCE_DESC bufferDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  796. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, bufferDesc,
  797. ppUavResource, ppUploadResource, ppReadBuffer);
  798. }
  799. // Create and return descriptor heaps for the given device
  800. // with the given number of resources and samples.
  801. // using some reasonable defaults
  802. void CreateDefaultDescHeaps(ID3D12Device *pDevice,
  803. int NumResources, int NumSamplers,
  804. ID3D12DescriptorHeap **ppResHeap, ID3D12DescriptorHeap **ppSampHeap) {
  805. // Describe and create descriptor heaps.
  806. ID3D12DescriptorHeap *pResHeap, *pSampHeap;
  807. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  808. heapDesc.NumDescriptors = NumResources;
  809. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  810. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  811. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pResHeap)));
  812. heapDesc.NumDescriptors = NumSamplers;
  813. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER;
  814. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pSampHeap)));
  815. *ppResHeap = pResHeap;
  816. *ppSampHeap = pSampHeap;
  817. }
  818. void CreateSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &baseHandle,
  819. DXGI_FORMAT format, D3D12_SRV_DIMENSION viewDimension, UINT numElements, UINT stride,
  820. const CComPtr<ID3D12Resource> pResource) {
  821. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  822. // Create SRV
  823. D3D12_SHADER_RESOURCE_VIEW_DESC srvDesc = {};
  824. srvDesc.Format = format;
  825. srvDesc.ViewDimension = viewDimension;
  826. srvDesc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING;
  827. switch (viewDimension) {
  828. case D3D12_SRV_DIMENSION_BUFFER:
  829. srvDesc.Buffer.FirstElement = 0;
  830. srvDesc.Buffer.NumElements = numElements;
  831. srvDesc.Buffer.StructureByteStride = stride;
  832. if (format == DXGI_FORMAT_R32_TYPELESS && stride == 0)
  833. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW;
  834. else
  835. srvDesc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE;
  836. break;
  837. case D3D12_SRV_DIMENSION_TEXTURE1D:
  838. srvDesc.Texture1D.MostDetailedMip = 0;
  839. srvDesc.Texture1D.MipLevels = 1;
  840. srvDesc.Texture1D.ResourceMinLODClamp = 0;
  841. break;
  842. case D3D12_SRV_DIMENSION_TEXTURE2D:
  843. srvDesc.Texture2D.MostDetailedMip = 0;
  844. srvDesc.Texture2D.MipLevels = 1;
  845. srvDesc.Texture2D.PlaneSlice = 0;
  846. srvDesc.Texture2D.ResourceMinLODClamp = 0;
  847. break;
  848. }
  849. pDevice->CreateShaderResourceView(pResource, &srvDesc, baseHandle);
  850. baseHandle.Offset(descriptorSize);
  851. }
  852. void CreateRawSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  853. UINT numElements, const CComPtr<ID3D12Resource> pResource) {
  854. CreateSRV(pDevice, heapStart, DXGI_FORMAT_R32_TYPELESS, D3D12_SRV_DIMENSION_BUFFER, numElements, 0, pResource);
  855. }
  856. void CreateStructSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  857. UINT numElements, UINT stride, const CComPtr<ID3D12Resource> pResource) {
  858. CreateSRV(pDevice, heapStart, DXGI_FORMAT_UNKNOWN, D3D12_SRV_DIMENSION_BUFFER, numElements, stride, pResource);
  859. }
  860. void CreateTypedSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  861. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  862. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_BUFFER, numElements, 0, pResource);
  863. }
  864. void CreateTex1DSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  865. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  866. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_TEXTURE1D, numElements, 0, pResource);
  867. }
  868. void CreateTex2DSRV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  869. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  870. CreateSRV(pDevice, heapStart, format, D3D12_SRV_DIMENSION_TEXTURE2D, numElements, 0, pResource);
  871. }
  872. void CreateUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &baseHandle,
  873. DXGI_FORMAT format, D3D12_UAV_DIMENSION viewDimension, UINT numElements, UINT stride,
  874. const CComPtr<ID3D12Resource> pResource) {
  875. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
  876. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  877. uavDesc.Format = format;
  878. uavDesc.ViewDimension = viewDimension;
  879. switch (viewDimension) {
  880. case D3D12_UAV_DIMENSION_BUFFER:
  881. uavDesc.Buffer.FirstElement = 0;
  882. uavDesc.Buffer.NumElements = numElements;
  883. uavDesc.Buffer.StructureByteStride = stride;
  884. if (format == DXGI_FORMAT_R32_TYPELESS && stride == 0)
  885. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  886. else
  887. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  888. break;
  889. case D3D12_UAV_DIMENSION_TEXTURE1D:
  890. uavDesc.Texture1D.MipSlice = 0;
  891. break;
  892. case D3D12_UAV_DIMENSION_TEXTURE2D:
  893. uavDesc.Texture2D.MipSlice = 0;
  894. uavDesc.Texture2D.PlaneSlice = 0;
  895. break;
  896. }
  897. pDevice->CreateUnorderedAccessView(pResource, nullptr, &uavDesc, baseHandle);
  898. baseHandle.Offset(descriptorSize);
  899. }
  900. void CreateRawUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  901. UINT numElements, const CComPtr<ID3D12Resource> pResource) {
  902. CreateUAV(pDevice, heapStart, DXGI_FORMAT_R32_TYPELESS, D3D12_UAV_DIMENSION_BUFFER, numElements, 0, pResource);
  903. }
  904. void CreateStructUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  905. UINT numElements, UINT stride, const CComPtr<ID3D12Resource> pResource) {
  906. CreateUAV(pDevice, heapStart, DXGI_FORMAT_UNKNOWN, D3D12_UAV_DIMENSION_BUFFER, numElements, stride, pResource);
  907. }
  908. void CreateTypedUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  909. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  910. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_BUFFER, numElements, 0, pResource);
  911. }
  912. void CreateTex1DUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  913. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  914. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_TEXTURE1D, numElements, 0, pResource);
  915. }
  916. void CreateTex2DUAV(ID3D12Device *pDevice, CD3DX12_CPU_DESCRIPTOR_HANDLE &heapStart,
  917. UINT numElements, DXGI_FORMAT format, const CComPtr<ID3D12Resource> pResource) {
  918. CreateUAV(pDevice, heapStart, format, D3D12_UAV_DIMENSION_TEXTURE2D, numElements, 0, pResource);
  919. }
  920. // Create Samplers for <pDevice> given the filter and border color information provided
  921. // using some reasonable defaults
  922. void CreateDefaultSamplers(ID3D12Device *pDevice, D3D12_CPU_DESCRIPTOR_HANDLE heapStart,
  923. D3D12_FILTER filters[], float BorderColors[], int NumSamplers) {
  924. CD3DX12_CPU_DESCRIPTOR_HANDLE sampHandle(heapStart);
  925. UINT descriptorSize = pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_SAMPLER);
  926. D3D12_SAMPLER_DESC sampDesc = {};
  927. sampDesc.Filter = D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT;
  928. sampDesc.AddressU = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  929. sampDesc.AddressV = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  930. sampDesc.AddressW = D3D12_TEXTURE_ADDRESS_MODE_BORDER;
  931. sampDesc.MipLODBias = 0;
  932. sampDesc.MaxAnisotropy = 1;
  933. sampDesc.ComparisonFunc = D3D12_COMPARISON_FUNC_EQUAL;
  934. sampDesc.MinLOD = 0;
  935. sampDesc.MaxLOD = 0;
  936. for (int i = 0; i < NumSamplers; i++) {
  937. sampDesc.Filter = filters[i];
  938. for (int j = 0; j < 4; j++)
  939. sampDesc.BorderColor[j] = BorderColors[i];
  940. pDevice->CreateSampler(&sampDesc, sampHandle);
  941. sampHandle = sampHandle.Offset(descriptorSize);
  942. }
  943. }
  944. template <typename TVertex, int len>
  945. void CreateVertexBuffer(ID3D12Device *pDevice, TVertex(&vertices)[len],
  946. ID3D12Resource **ppVertexBuffer,
  947. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView) {
  948. size_t vertexBufferSize = sizeof(vertices);
  949. CComPtr<ID3D12Resource> pVertexBuffer;
  950. CD3DX12_HEAP_PROPERTIES heapProps(D3D12_HEAP_TYPE_UPLOAD);
  951. CD3DX12_RESOURCE_DESC bufferDesc(
  952. CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize));
  953. VERIFY_SUCCEEDED(pDevice->CreateCommittedResource(
  954. &heapProps, D3D12_HEAP_FLAG_NONE, &bufferDesc,
  955. D3D12_RESOURCE_STATE_GENERIC_READ, nullptr,
  956. IID_PPV_ARGS(&pVertexBuffer)));
  957. UINT8 *pVertexDataBegin;
  958. CD3DX12_RANGE readRange(0, 0);
  959. VERIFY_SUCCEEDED(pVertexBuffer->Map(
  960. 0, &readRange, reinterpret_cast<void **>(&pVertexDataBegin)));
  961. memcpy(pVertexDataBegin, vertices, vertexBufferSize);
  962. pVertexBuffer->Unmap(0, nullptr);
  963. // Initialize the vertex buffer view.
  964. pVertexBufferView->BufferLocation = pVertexBuffer->GetGPUVirtualAddress();
  965. pVertexBufferView->StrideInBytes = sizeof(TVertex);
  966. pVertexBufferView->SizeInBytes = (UINT)vertexBufferSize;
  967. *ppVertexBuffer = pVertexBuffer.Detach();
  968. }
  969. // Requires Anniversary Edition headers, so simplifying things for current setup.
  970. const UINT D3D12_FEATURE_D3D12_OPTIONS1 = 8;
  971. struct D3D12_FEATURE_DATA_D3D12_OPTIONS1 {
  972. BOOL WaveOps;
  973. UINT WaveLaneCountMin;
  974. UINT WaveLaneCountMax;
  975. UINT TotalLaneCount;
  976. BOOL ExpandedComputeResourceStates;
  977. BOOL Int64ShaderOps;
  978. };
  979. bool IsDeviceBasicAdapter(ID3D12Device *pDevice) {
  980. CComPtr<IDXGIFactory4> factory;
  981. VERIFY_SUCCEEDED(CreateDXGIFactory1(IID_PPV_ARGS(&factory)));
  982. LUID adapterID = pDevice->GetAdapterLuid();
  983. CComPtr<IDXGIAdapter1> adapter;
  984. factory->EnumAdapterByLuid(adapterID, IID_PPV_ARGS(&adapter));
  985. DXGI_ADAPTER_DESC1 AdapterDesc;
  986. VERIFY_SUCCEEDED(adapter->GetDesc1(&AdapterDesc));
  987. return (AdapterDesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE);
  988. }
  989. bool DoesDeviceSupportInt64(ID3D12Device *pDevice) {
  990. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  991. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  992. return false;
  993. return O.Int64ShaderOps != FALSE;
  994. }
  995. bool DoesDeviceSupportDouble(ID3D12Device *pDevice) {
  996. D3D12_FEATURE_DATA_D3D12_OPTIONS O;
  997. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS, &O, sizeof(O))))
  998. return false;
  999. return O.DoublePrecisionFloatShaderOps != FALSE;
  1000. }
  1001. bool DoesDeviceSupportWaveOps(ID3D12Device *pDevice) {
  1002. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1003. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1004. return false;
  1005. return O.WaveOps != FALSE;
  1006. }
  1007. bool DoesDeviceSupportBarycentrics(ID3D12Device *pDevice) {
  1008. D3D12_FEATURE_DATA_D3D12_OPTIONS3 O;
  1009. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS3, &O, sizeof(O))))
  1010. return false;
  1011. return O.BarycentricsSupported != FALSE;
  1012. }
  1013. bool DoesDeviceSupportNative16bitOps(ID3D12Device *pDevice) {
  1014. D3D12_FEATURE_DATA_D3D12_OPTIONS4 O;
  1015. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS4, &O, sizeof(O))))
  1016. return false;
  1017. return O.Native16BitShaderOpsSupported != FALSE;
  1018. }
  1019. bool DoesDeviceSupportMeshShaders(ID3D12Device *pDevice) {
  1020. #if defined(NTDDI_WIN10_VB) && WDK_NTDDI_VERSION >= NTDDI_WIN10_VB
  1021. D3D12_FEATURE_DATA_D3D12_OPTIONS7 O7;
  1022. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS7, &O7, sizeof(O7))))
  1023. return false;
  1024. return O7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED;
  1025. #else
  1026. UNREFERENCED_PARAMETER(pDevice);
  1027. return false;
  1028. #endif
  1029. }
  1030. bool DoesDeviceSupportRayTracing(ID3D12Device *pDevice) {
  1031. #if WDK_NTDDI_VERSION > NTDDI_WIN10_RS4
  1032. D3D12_FEATURE_DATA_D3D12_OPTIONS5 O5;
  1033. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS5, &O5, sizeof(O5))))
  1034. return false;
  1035. return O5.RaytracingTier != D3D12_RAYTRACING_TIER_NOT_SUPPORTED;
  1036. #else
  1037. UNREFERENCED_PARAMETER(pDevice);
  1038. return false;
  1039. #endif
  1040. }
  1041. bool DoesDeviceSupportMeshAmpDerivatives(ID3D12Device *pDevice) {
  1042. #if defined(NTDDI_WIN10_FE) && WDK_NTDDI_VERSION >= NTDDI_WIN10_FE
  1043. D3D12_FEATURE_DATA_D3D12_OPTIONS7 O7;
  1044. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1045. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS7, &O7, sizeof(O7))) ||
  1046. FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1047. return false;
  1048. return O7.MeshShaderTier != D3D12_MESH_SHADER_TIER_NOT_SUPPORTED &&
  1049. O9.DerivativesInMeshAndAmplificationShadersSupported != FALSE;
  1050. #else
  1051. UNREFERENCED_PARAMETER(pDevice);
  1052. return false;
  1053. #endif
  1054. }
  1055. bool DoesDeviceSupportTyped64Atomics(ID3D12Device *pDevice) {
  1056. #if defined(NTDDI_WIN10_FE) && WDK_NTDDI_VERSION >= NTDDI_WIN10_FE
  1057. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1058. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1059. return false;
  1060. return O9.AtomicInt64OnTypedResourceSupported != FALSE;
  1061. #else
  1062. UNREFERENCED_PARAMETER(pDevice);
  1063. return false;
  1064. #endif
  1065. }
  1066. bool DoesDeviceSupportHeap64Atomics(ID3D12Device *pDevice) {
  1067. #if defined(NTDDI_WIN10_CO) && WDK_NTDDI_VERSION >= NTDDI_WIN10_CO
  1068. D3D12_FEATURE_DATA_D3D12_OPTIONS11 O11;
  1069. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS11, &O11, sizeof(O11))))
  1070. return false;
  1071. return O11.AtomicInt64OnDescriptorHeapResourceSupported != FALSE;
  1072. #else
  1073. UNREFERENCED_PARAMETER(pDevice);
  1074. return false;
  1075. #endif
  1076. }
  1077. bool DoesDeviceSupportShared64Atomics(ID3D12Device *pDevice) {
  1078. #if defined(NTDDI_WIN10_FE) && WDK_NTDDI_VERSION >= NTDDI_WIN10_FE
  1079. D3D12_FEATURE_DATA_D3D12_OPTIONS9 O9;
  1080. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS9, &O9, sizeof(O9))))
  1081. return false;
  1082. return O9.AtomicInt64OnGroupSharedSupported != FALSE;
  1083. #else
  1084. UNREFERENCED_PARAMETER(pDevice);
  1085. return false;
  1086. #endif
  1087. }
  1088. #ifndef _HLK_CONF
  1089. void DXBCFromText(LPCSTR pText, LPCWSTR pEntryPoint, LPCWSTR pTargetProfile, ID3DBlob **ppBlob) {
  1090. CW2A pEntryPointA(pEntryPoint, CP_UTF8);
  1091. CW2A pTargetProfileA(pTargetProfile, CP_UTF8);
  1092. CComPtr<ID3DBlob> pErrors;
  1093. D3D_SHADER_MACRO d3dMacro[2];
  1094. ZeroMemory(d3dMacro, sizeof(d3dMacro));
  1095. d3dMacro[0].Definition = "1";
  1096. d3dMacro[0].Name = "USING_DXBC";
  1097. HRESULT hr = D3DCompile(pText, strlen(pText), "hlsl.hlsl", d3dMacro, nullptr, pEntryPointA, pTargetProfileA, 0, 0, ppBlob, &pErrors);
  1098. if (pErrors != nullptr) {
  1099. CA2W errors((char *)pErrors->GetBufferPointer(), CP_ACP);
  1100. LogCommentFmt(L"Compilation failure: %s", errors.m_szBuffer);
  1101. }
  1102. VERIFY_SUCCEEDED(hr);
  1103. }
  1104. #endif
  1105. HRESULT EnableDebugLayer() {
  1106. // The debug layer does net yet validate DXIL programs that require rewriting,
  1107. // but basic logging should work properly.
  1108. HRESULT hr = S_FALSE;
  1109. if (UseDebugIfaces()) {
  1110. CComPtr<ID3D12Debug> debugController;
  1111. hr = D3D12GetDebugInterface(IID_PPV_ARGS(&debugController));
  1112. if (SUCCEEDED(hr)) {
  1113. debugController->EnableDebugLayer();
  1114. hr = S_OK;
  1115. }
  1116. }
  1117. return hr;
  1118. }
  1119. static HRESULT EnableExperimentalShaderModels() {
  1120. HMODULE hRuntime = LoadLibraryW(L"d3d12.dll");
  1121. if (hRuntime == NULL) {
  1122. return HRESULT_FROM_WIN32(GetLastError());
  1123. }
  1124. D3D12EnableExperimentalFeaturesFn pD3D12EnableExperimentalFeatures =
  1125. (D3D12EnableExperimentalFeaturesFn)GetProcAddress(
  1126. hRuntime, "D3D12EnableExperimentalFeatures");
  1127. if (pD3D12EnableExperimentalFeatures == nullptr) {
  1128. FreeLibrary(hRuntime);
  1129. return HRESULT_FROM_WIN32(GetLastError());
  1130. }
  1131. HRESULT hr = pD3D12EnableExperimentalFeatures(
  1132. 1, &D3D12ExperimentalShaderModelsID, nullptr, nullptr);
  1133. FreeLibrary(hRuntime);
  1134. return hr;
  1135. }
  1136. HRESULT EnableExperimentalMode() {
  1137. if (m_ExperimentalModeEnabled) {
  1138. return S_OK;
  1139. }
  1140. if (!GetTestParamBool(L"ExperimentalShaders")) {
  1141. return S_FALSE;
  1142. }
  1143. HRESULT hr = EnableExperimentalShaderModels();
  1144. if (SUCCEEDED(hr)) {
  1145. m_ExperimentalModeEnabled = true;
  1146. }
  1147. return hr;
  1148. }
  1149. struct FenceObj {
  1150. HANDLE m_fenceEvent = NULL;
  1151. CComPtr<ID3D12Fence> m_fence;
  1152. UINT64 m_fenceValue;
  1153. ~FenceObj() {
  1154. if (m_fenceEvent) CloseHandle(m_fenceEvent);
  1155. }
  1156. };
  1157. void InitFenceObj(ID3D12Device *pDevice, FenceObj *pObj) {
  1158. pObj->m_fenceValue = 1;
  1159. VERIFY_SUCCEEDED(pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE,
  1160. IID_PPV_ARGS(&pObj->m_fence)));
  1161. // Create an event handle to use for frame synchronization.
  1162. pObj->m_fenceEvent = CreateEvent(nullptr, FALSE, FALSE, nullptr);
  1163. if (pObj->m_fenceEvent == nullptr) {
  1164. VERIFY_SUCCEEDED(HRESULT_FROM_WIN32(GetLastError()));
  1165. }
  1166. }
  1167. void ReadHlslDataIntoNewStream(LPCWSTR relativePath, IStream **ppStream) {
  1168. VERIFY_SUCCEEDED(m_support.Initialize());
  1169. CComPtr<IDxcLibrary> pLibrary;
  1170. CComPtr<IDxcBlobEncoding> pBlob;
  1171. CComPtr<IStream> pStream;
  1172. std::wstring path = GetPathToHlslDataFile(relativePath);
  1173. VERIFY_SUCCEEDED(m_support.CreateInstance(CLSID_DxcLibrary, &pLibrary));
  1174. VERIFY_SUCCEEDED(pLibrary->CreateBlobFromFile(path.c_str(), nullptr, &pBlob));
  1175. VERIFY_SUCCEEDED(pLibrary->CreateStreamFromBlobReadOnly(pBlob, &pStream));
  1176. *ppStream = pStream.Detach();
  1177. }
  1178. void RecordRenderAndReadback(ID3D12GraphicsCommandList *pList,
  1179. ID3D12DescriptorHeap *pRtvHeap,
  1180. UINT rtvDescriptorSize,
  1181. UINT instanceCount,
  1182. D3D12_VERTEX_BUFFER_VIEW *pVertexBufferView,
  1183. ID3D12RootSignature *pRootSig,
  1184. ID3D12Resource *pRenderTarget,
  1185. ID3D12Resource *pReadBuffer) {
  1186. D3D12_RESOURCE_DESC rtDesc = pRenderTarget->GetDesc();
  1187. D3D12_VIEWPORT viewport;
  1188. D3D12_RECT scissorRect;
  1189. memset(&viewport, 0, sizeof(viewport));
  1190. viewport.Height = (float)rtDesc.Height;
  1191. viewport.Width = (float)rtDesc.Width;
  1192. viewport.MaxDepth = 1.0f;
  1193. memset(&scissorRect, 0, sizeof(scissorRect));
  1194. scissorRect.right = (long)rtDesc.Width;
  1195. scissorRect.bottom = rtDesc.Height;
  1196. if (pRootSig != nullptr) {
  1197. pList->SetGraphicsRootSignature(pRootSig);
  1198. }
  1199. pList->RSSetViewports(1, &viewport);
  1200. pList->RSSetScissorRects(1, &scissorRect);
  1201. // Indicate that the buffer will be used as a render target.
  1202. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_RENDER_TARGET);
  1203. CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHandle(pRtvHeap->GetCPUDescriptorHandleForHeapStart(), 0, rtvDescriptorSize);
  1204. pList->OMSetRenderTargets(1, &rtvHandle, FALSE, nullptr);
  1205. pList->ClearRenderTargetView(rtvHandle, ClearColor, 0, nullptr);
  1206. pList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
  1207. pList->IASetVertexBuffers(0, 1, pVertexBufferView);
  1208. pList->DrawInstanced(3, instanceCount, 0, 0);
  1209. // Transition to copy source and copy into read-back buffer.
  1210. RecordTransitionBarrier(pList, pRenderTarget, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1211. // Copy into read-back buffer.
  1212. UINT64 rowPitch = rtDesc.Width * 4;
  1213. if (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT)
  1214. rowPitch += D3D12_TEXTURE_DATA_PITCH_ALIGNMENT - (rowPitch % D3D12_TEXTURE_DATA_PITCH_ALIGNMENT);
  1215. D3D12_PLACED_SUBRESOURCE_FOOTPRINT Footprint;
  1216. Footprint.Offset = 0;
  1217. Footprint.Footprint = CD3DX12_SUBRESOURCE_FOOTPRINT(DXGI_FORMAT_R8G8B8A8_UNORM, (UINT)rtDesc.Width, rtDesc.Height, 1, (UINT)rowPitch);
  1218. CD3DX12_TEXTURE_COPY_LOCATION DstLoc(pReadBuffer, Footprint);
  1219. CD3DX12_TEXTURE_COPY_LOCATION SrcLoc(pRenderTarget, 0);
  1220. pList->CopyTextureRegion(&DstLoc, 0, 0, 0, &SrcLoc, nullptr);
  1221. }
  1222. void RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR shader, std::vector<uint32_t> &values);
  1223. void RunLifetimeIntrinsicTest(ID3D12Device *pDevice, LPCSTR shader, D3D_SHADER_MODEL shaderModel, bool useLibTarget, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values);
  1224. void RunLifetimeIntrinsicComputeTest(ID3D12Device *pDevice, LPCSTR pShader, CComPtr<ID3D12DescriptorHeap>& pUavHeap, CComPtr<ID3D12RootSignature>& pRootSignature,
  1225. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values);
  1226. void RunLifetimeIntrinsicLibTest(ID3D12Device *pDevice0, LPCSTR pShader, CComPtr<ID3D12RootSignature>& pRootSignature,
  1227. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions);
  1228. void SetDescriptorHeap(ID3D12GraphicsCommandList *pCommandList, ID3D12DescriptorHeap *pHeap) {
  1229. ID3D12DescriptorHeap *const pHeaps[1] = { pHeap };
  1230. pCommandList->SetDescriptorHeaps(1, pHeaps);
  1231. }
  1232. void WaitForSignal(ID3D12CommandQueue *pCQ, FenceObj &FO) {
  1233. ::WaitForSignal(pCQ, FO.m_fence, FO.m_fenceEvent, FO.m_fenceValue++);
  1234. }
  1235. };
  1236. #define WAVE_INTRINSIC_DXBC_GUARD \
  1237. "#ifdef USING_DXBC\r\n" \
  1238. "uint WaveGetLaneIndex() { return 1; }\r\n" \
  1239. "uint WaveReadLaneFirst(uint u) { return u; }\r\n" \
  1240. "bool WaveIsFirstLane() { return true; }\r\n" \
  1241. "uint WaveGetLaneCount() { return 1; }\r\n" \
  1242. "uint WaveReadLaneAt(uint n, uint u) { return u; }\r\n" \
  1243. "bool WaveActiveAnyTrue(bool b) { return b; }\r\n" \
  1244. "bool WaveActiveAllTrue(bool b) { return false; }\r\n" \
  1245. "uint WaveActiveAllEqual(uint u) { return u; }\r\n" \
  1246. "uint4 WaveActiveBallot(bool b) { return 1; }\r\n" \
  1247. "uint WaveActiveCountBits(uint u) { return 1; }\r\n" \
  1248. "uint WaveActiveSum(uint u) { return 1; }\r\n" \
  1249. "uint WaveActiveProduct(uint u) { return 1; }\r\n" \
  1250. "uint WaveActiveBitAnd(uint u) { return 1; }\r\n" \
  1251. "uint WaveActiveBitOr(uint u) { return 1; }\r\n" \
  1252. "uint WaveActiveBitXor(uint u) { return 1; }\r\n" \
  1253. "uint WaveActiveMin(uint u) { return 1; }\r\n" \
  1254. "uint WaveActiveMax(uint u) { return 1; }\r\n" \
  1255. "uint WavePrefixCountBits(uint u) { return 1; }\r\n" \
  1256. "uint WavePrefixSum(uint u) { return 1; }\r\n" \
  1257. "uint WavePrefixProduct(uint u) { return 1; }\r\n" \
  1258. "uint QuadReadLaneAt(uint a, uint u) { return 1; }\r\n" \
  1259. "uint QuadReadAcrossX(uint u) { return 1; }\r\n" \
  1260. "uint QuadReadAcrossY(uint u) { return 1; }\r\n" \
  1261. "uint QuadReadAcrossDiagonal(uint u) { return 1; }\r\n" \
  1262. "#endif\r\n"
  1263. static void SetupComputeValuePattern(std::vector<uint32_t> &values,
  1264. size_t count) {
  1265. values.resize(count); // one element per dispatch group, in bytes
  1266. for (size_t i = 0; i < count; ++i) {
  1267. values[i] = (uint32_t)i;
  1268. }
  1269. }
  1270. bool ExecutionTest::ExecutionTestClassSetup() {
  1271. return DivergentClassSetup();
  1272. }
  1273. void ExecutionTest::RunRWByteBufferComputeTest(ID3D12Device *pDevice, LPCSTR pShader, std::vector<uint32_t> &values) {
  1274. static const int DispatchGroupX = 1;
  1275. static const int DispatchGroupY = 1;
  1276. static const int DispatchGroupZ = 1;
  1277. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1278. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1279. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1280. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1281. UINT uavDescriptorSize;
  1282. FenceObj FO;
  1283. const UINT valueSizeInBytes = (UINT)values.size() * sizeof(uint32_t);
  1284. CreateComputeCommandQueue(pDevice, L"RunRWByteBufferComputeTest Command Queue", &pCommandQueue);
  1285. InitFenceObj(pDevice, &FO);
  1286. // Describe and create a UAV descriptor heap.
  1287. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1288. heapDesc.NumDescriptors = 1;
  1289. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1290. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1291. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1292. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1293. // Create root signature.
  1294. CComPtr<ID3D12RootSignature> pRootSignature;
  1295. {
  1296. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1297. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1298. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1299. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1300. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1301. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  1302. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1303. }
  1304. // Create pipeline state object.
  1305. CComPtr<ID3D12PipelineState> pComputeState;
  1306. CreateComputePSO(pDevice, pRootSignature, pShader, L"cs_6_0", &pComputeState);
  1307. // Create a command allocator and list for compute.
  1308. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1309. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1310. pCommandList->SetName(L"ExecutionTest::RunRWByteButterComputeTest Command List");
  1311. // Set up UAV resource.
  1312. CComPtr<ID3D12Resource> pUavResource;
  1313. CComPtr<ID3D12Resource> pReadBuffer;
  1314. CComPtr<ID3D12Resource> pUploadResource;
  1315. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  1316. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunRWByteBufferComputeText UAV"));
  1317. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunRWByteBufferComputeText UAV Read Buffer"));
  1318. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunRWByteBufferComputeText UAV Upload Buffer"));
  1319. // Close the command list and execute it to perform the GPU setup.
  1320. pCommandList->Close();
  1321. ExecuteCommandList(pCommandQueue, pCommandList);
  1322. WaitForSignal(pCommandQueue, FO);
  1323. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1324. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1325. // Run the compute shader and copy the results back to readable memory.
  1326. {
  1327. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1328. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1329. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1330. uavDesc.Buffer.FirstElement = 0;
  1331. uavDesc.Buffer.NumElements = (UINT)values.size();
  1332. uavDesc.Buffer.StructureByteStride = 0;
  1333. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1334. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  1335. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1336. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1337. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1338. SetDescriptorHeap(pCommandList, pUavHeap);
  1339. pCommandList->SetComputeRootSignature(pRootSignature);
  1340. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1341. }
  1342. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1343. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1344. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1345. pCommandList->Close();
  1346. ExecuteCommandList(pCommandQueue, pCommandList);
  1347. WaitForSignal(pCommandQueue, FO);
  1348. {
  1349. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1350. uint32_t *pData = (uint32_t *)mappedData.data();
  1351. memcpy(values.data(), pData, (size_t)valueSizeInBytes);
  1352. }
  1353. WaitForSignal(pCommandQueue, FO);
  1354. }
  1355. void ExecutionTest::RunLifetimeIntrinsicComputeTest(ID3D12Device *pDevice, LPCSTR pShader, CComPtr<ID3D12DescriptorHeap>& pUavHeap, CComPtr<ID3D12RootSignature>& pRootSignature,
  1356. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values) {
  1357. // Create command queue.
  1358. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1359. CreateComputeCommandQueue(pDevice, L"RunLifetimeIntrinsicTest Command Queue", &pCommandQueue);
  1360. FenceObj FO;
  1361. InitFenceObj(pDevice, &FO);
  1362. // Compile shader "main" and create pipeline state object.
  1363. CComPtr<ID3D12PipelineState> pComputeState;
  1364. CreateComputePSO(pDevice, pRootSignature, pShader, pTargetProfile, &pComputeState, pOptions, numOptions);
  1365. // Create a command allocator and list for compute.
  1366. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1367. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1368. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  1369. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  1370. pCommandList->SetName(L"ExecutionTest::RunLifetimeIntrinsicTest Command List");
  1371. // Set up UAV resource.
  1372. const UINT valueSizeInBytes = (UINT)values.size() * sizeof(uint32_t);
  1373. CComPtr<ID3D12Resource> pUavResource;
  1374. CComPtr<ID3D12Resource> pReadBuffer;
  1375. CComPtr<ID3D12Resource> pUploadResource;
  1376. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  1377. VERIFY_SUCCEEDED(pUavResource->SetName(L"RunLifetimeIntrinsicTest UAV"));
  1378. VERIFY_SUCCEEDED(pReadBuffer->SetName(L"RunLifetimeIntrinsicTest UAV Read Buffer"));
  1379. VERIFY_SUCCEEDED(pUploadResource->SetName(L"RunLifetimeIntrinsicTest UAV Upload Buffer"));
  1380. // Close the command list and execute it to perform the GPU setup.
  1381. pCommandList->Close();
  1382. ExecuteCommandList(pCommandQueue, pCommandList);
  1383. WaitForSignal(pCommandQueue, FO);
  1384. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  1385. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  1386. // Run the compute shader and copy the results back to readable memory.
  1387. {
  1388. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  1389. uavDesc.Format = DXGI_FORMAT_R32_TYPELESS;
  1390. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  1391. uavDesc.Buffer.FirstElement = 0;
  1392. uavDesc.Buffer.NumElements = (UINT)values.size();
  1393. uavDesc.Buffer.StructureByteStride = 0;
  1394. uavDesc.Buffer.CounterOffsetInBytes = 0;
  1395. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_RAW;
  1396. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  1397. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  1398. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  1399. SetDescriptorHeap(pCommandList, pUavHeap);
  1400. pCommandList->SetComputeRootSignature(pRootSignature);
  1401. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  1402. }
  1403. static const int DispatchGroupX = 1;
  1404. static const int DispatchGroupY = 1;
  1405. static const int DispatchGroupZ = 1;
  1406. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  1407. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  1408. pCommandList->CopyResource(pReadBuffer, pUavResource);
  1409. pCommandList->Close();
  1410. ExecuteCommandList(pCommandQueue, pCommandList);
  1411. WaitForSignal(pCommandQueue, FO);
  1412. {
  1413. MappedData mappedData(pReadBuffer, valueSizeInBytes);
  1414. uint32_t *pData = (uint32_t *)mappedData.data();
  1415. memcpy(values.data(), pData, (size_t)valueSizeInBytes);
  1416. }
  1417. WaitForSignal(pCommandQueue, FO);
  1418. }
  1419. void ExecutionTest::RunLifetimeIntrinsicLibTest(ID3D12Device *pDevice0, LPCSTR pShader, CComPtr<ID3D12RootSignature>& pRootSignature,
  1420. LPCWSTR pTargetProfile, LPCWSTR *pOptions, int numOptions) {
  1421. CComPtr<ID3D12Device5> pDevice;
  1422. VERIFY_SUCCEEDED(pDevice0->QueryInterface(IID_PPV_ARGS(&pDevice)));
  1423. // Create command queue.
  1424. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1425. CreateCommandQueue(pDevice, L"RunLifetimeIntrinsicTest Command Queue", &pCommandQueue, D3D12_COMMAND_LIST_TYPE_DIRECT);
  1426. FenceObj FO;
  1427. InitFenceObj(pDevice, &FO);
  1428. // Compile raygen shader.
  1429. CComPtr<ID3DBlob> pShaderLib;
  1430. CompileFromText(pShader, L"RayGen", pTargetProfile, &pShaderLib, pOptions, numOptions);
  1431. // Describe and create the RT pipeline state object (RTPSO).
  1432. CD3DX12_STATE_OBJECT_DESC stateObjectDesc(D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE);
  1433. auto lib = stateObjectDesc.CreateSubobject<CD3DX12_DXIL_LIBRARY_SUBOBJECT>();
  1434. CD3DX12_SHADER_BYTECODE byteCode(pShaderLib);
  1435. lib->SetDXILLibrary(&byteCode);
  1436. lib->DefineExport(L"RayGen");
  1437. const int payloadCount = 4;
  1438. const int attributeCount = 2;
  1439. const int maxRecursion = 2;
  1440. stateObjectDesc.CreateSubobject<CD3DX12_RAYTRACING_SHADER_CONFIG_SUBOBJECT>()->Config(payloadCount * sizeof(float), attributeCount * sizeof(float));
  1441. stateObjectDesc.CreateSubobject<CD3DX12_RAYTRACING_PIPELINE_CONFIG_SUBOBJECT>()->Config(maxRecursion);
  1442. // Create (local!) root sig subobject and associate with shader.
  1443. auto localRootSigSubObj = stateObjectDesc.CreateSubobject<CD3DX12_LOCAL_ROOT_SIGNATURE_SUBOBJECT>();
  1444. localRootSigSubObj->SetRootSignature(pRootSignature);
  1445. auto x = stateObjectDesc.CreateSubobject<CD3DX12_SUBOBJECT_TO_EXPORTS_ASSOCIATION_SUBOBJECT>();
  1446. x->SetSubobjectToAssociate(*localRootSigSubObj);
  1447. x->AddExport(L"RayGen");
  1448. CComPtr<ID3D12StateObject> pStateObject;
  1449. VERIFY_SUCCEEDED(pDevice->CreateStateObject(stateObjectDesc, IID_PPV_ARGS(&pStateObject)));
  1450. // Create a command allocator and list.
  1451. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1452. CComPtr<ID3D12GraphicsCommandList4> pCommandList;
  1453. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&pCommandAllocator)));
  1454. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, pCommandAllocator, nullptr, IID_PPV_ARGS(&pCommandList)));
  1455. pCommandList->SetPipelineState1(pStateObject);
  1456. pCommandList->SetName(L"ExecutionTest::RunLifetimeIntrinsicTest Command List");
  1457. // Close the command list and execute it to kick-off compilation in the driver.
  1458. // NOTE: We don't care about anything else, so we're not setting up any resources and don't actually execute the shader.
  1459. pCommandList->Close();
  1460. ExecuteCommandList(pCommandQueue, pCommandList);
  1461. WaitForSignal(pCommandQueue, FO);
  1462. }
  1463. void ExecutionTest::RunLifetimeIntrinsicTest(ID3D12Device *pDevice, LPCSTR pShader, D3D_SHADER_MODEL shaderModel, bool useLibTarget,
  1464. LPCWSTR *pOptions, int numOptions, std::vector<uint32_t> &values) {
  1465. LPCWSTR pTargetProfile;
  1466. switch (shaderModel) {
  1467. default: pTargetProfile = useLibTarget ? L"lib_6_3" : L"cs_6_0"; break; // Default to 6.3 for lib, 6.0 otherwise.
  1468. case D3D_SHADER_MODEL_6_0: pTargetProfile = useLibTarget ? L"lib_6_0" : L"cs_6_0"; break;
  1469. case D3D_SHADER_MODEL_6_3: pTargetProfile = useLibTarget ? L"lib_6_3" : L"cs_6_3"; break;
  1470. case D3D_SHADER_MODEL_6_5: pTargetProfile = useLibTarget ? L"lib_6_5" : L"cs_6_5"; break;
  1471. case D3D_SHADER_MODEL_6_6: pTargetProfile = useLibTarget ? L"lib_6_6" : L"cs_6_6"; break;
  1472. }
  1473. // Describe a UAV descriptor heap.
  1474. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1475. heapDesc.NumDescriptors = 1;
  1476. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1477. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1478. // Create the UAV descriptor heap.
  1479. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1480. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1481. // Create root signature.
  1482. CComPtr<ID3D12RootSignature> pRootSignature;
  1483. {
  1484. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1485. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1486. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1487. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1488. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1489. D3D12_ROOT_SIGNATURE_FLAGS rootSigFlag = useLibTarget ? D3D12_ROOT_SIGNATURE_FLAG_LOCAL_ROOT_SIGNATURE : D3D12_ROOT_SIGNATURE_FLAG_NONE;
  1490. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, rootSigFlag);
  1491. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  1492. }
  1493. if (useLibTarget) {
  1494. RunLifetimeIntrinsicLibTest(pDevice, pShader, pRootSignature, pTargetProfile,
  1495. pOptions, numOptions);
  1496. } else {
  1497. RunLifetimeIntrinsicComputeTest(pDevice, pShader, pUavHeap, pRootSignature, pTargetProfile,
  1498. pOptions, numOptions, values);
  1499. }
  1500. }
  1501. TEST_F(ExecutionTest, LifetimeIntrinsicTest) {
  1502. // The only thing we test here is that existence of lifetime intrinsics or
  1503. // their fallback replacement (store undef or store zeroinitializer) do not
  1504. // cause any issues in the runtime and driver stack.
  1505. // The easiest way to force placement of intrinsics is to create an array in
  1506. // a local scope that is dynamically indexed. It must not be optimized away,
  1507. // so we do some bogus initialization that prevents this. Since all the code
  1508. // is guarded by a conditional that is dynamically always false, the actual
  1509. // effect of the shader is that the same value that was read is written back.
  1510. static const char* pShader = R"(
  1511. RWByteAddressBuffer g_bab : register(u0);
  1512. void fn(uint GI) {
  1513. const uint addr = GI * 4;
  1514. const int val = g_bab.Load(addr);
  1515. int res = val;
  1516. if (val < 0) { // Never true.
  1517. int arr[200];
  1518. for (int i = 0; i < 200; ++i) {
  1519. arr[i] = arr[val - i];
  1520. }
  1521. res += arr[val];
  1522. }
  1523. g_bab.Store(addr, (uint)res);
  1524. }
  1525. [numthreads(8,8,1)]
  1526. void main(uint GI : SV_GroupIndex) {
  1527. fn(GI);
  1528. }
  1529. [shader("raygeneration")]
  1530. void RayGen() {
  1531. const uint d = DispatchRaysIndex().x;
  1532. const uint g = g > 64 ? 63 : g;
  1533. fn(g);
  1534. }
  1535. )";
  1536. static const int NumThreadsX = 8;
  1537. static const int NumThreadsY = 8;
  1538. static const int NumThreadsZ = 1;
  1539. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1540. static const int DispatchGroupCount = 1;
  1541. CComPtr<ID3D12Device> pDevice;
  1542. bool bSM_6_6_Supported = CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6, false);
  1543. bool bSM_6_3_Supported = bSM_6_6_Supported;
  1544. if (!bSM_6_6_Supported) {
  1545. // Try 6.3 for downlevel DXR case
  1546. bSM_6_3_Supported = CreateDevice(&pDevice, D3D_SHADER_MODEL_6_3, false);
  1547. }
  1548. if (!bSM_6_3_Supported) {
  1549. // Otherwise, 6.0 better be supported for compute case
  1550. VERIFY_IS_TRUE(CreateDevice(&pDevice, D3D_SHADER_MODEL_6_0, false));
  1551. }
  1552. bool bDXRSupported = bSM_6_3_Supported && DoesDeviceSupportRayTracing(pDevice);
  1553. if (GetTestParamUseWARP(UseWarpByDefault()) || IsDeviceBasicAdapter(pDevice)) {
  1554. WEX::Logging::Log::Comment(L"WARP has a known issue with LifetimeIntrinsicTest.");
  1555. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  1556. return;
  1557. }
  1558. if (!bSM_6_6_Supported) {
  1559. WEX::Logging::Log::Comment(L"Native lifetime markers skipped, device does not support SM 6.6");
  1560. }
  1561. if (!bDXRSupported) {
  1562. WEX::Logging::Log::Comment(L"DXR lifetime tests skipped, device does not support DXR");
  1563. }
  1564. std::vector<uint32_t> values;
  1565. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1566. // Run a number of tests for different configurations that will cause
  1567. // lifetime intrinsics to be:
  1568. // - placed directly
  1569. // - translated to an undef store
  1570. // - translated to a zeroinitializer store
  1571. // against compute and DXR targets, downlevel and SM 6.6:
  1572. // - downlevel: cs_6_0, lib_6_3 (DXR)
  1573. // - cs_6_6, lib_6_6 (DXR)
  1574. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1575. LPCWSTR optsBase[] = {L"-enable-lifetime-markers"};
  1576. LPCWSTR optsZeroStore[] = {L"-enable-lifetime-markers", L"-force-zero-store-lifetimes"};
  1577. WEX::Logging::Log::Comment(L"==== cs_6_0 with default translation");
  1578. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_0, false,
  1579. optsBase, _countof(optsBase), values);
  1580. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1581. if (bDXRSupported) {
  1582. WEX::Logging::Log::Comment(L"==== DXR lib_6_3 with default translation");
  1583. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_3, true,
  1584. optsBase, _countof(optsBase), values);
  1585. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1586. }
  1587. WEX::Logging::Log::Comment(L"==== cs_6_0 with zeroinitializer translation");
  1588. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_0, false,
  1589. optsZeroStore, _countof(optsZeroStore), values);
  1590. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1591. if (bDXRSupported) {
  1592. WEX::Logging::Log::Comment(L"==== DXR lib_6_3 with zeroinitializer translation");
  1593. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_3, true,
  1594. optsZeroStore, _countof(optsZeroStore), values);
  1595. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1596. }
  1597. if (bSM_6_6_Supported) {
  1598. WEX::Logging::Log::Comment(L"==== cs_6_6 with zeroinitializer translation");
  1599. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_6, false,
  1600. optsZeroStore, _countof(optsZeroStore), values);
  1601. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1602. if (bDXRSupported) {
  1603. WEX::Logging::Log::Comment(L"==== DXR lib_6_6 with zeroinitializer translation");
  1604. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_6, true,
  1605. optsZeroStore, _countof(optsZeroStore), values);
  1606. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1607. }
  1608. WEX::Logging::Log::Comment(L"==== cs_6_6 with native lifetime markers");
  1609. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_6, false,
  1610. optsBase, _countof(optsBase), values);
  1611. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1612. if (bDXRSupported) {
  1613. WEX::Logging::Log::Comment(L"==== DXR lib_6_6 with native lifetime markers");
  1614. RunLifetimeIntrinsicTest(pDevice, pShader, D3D_SHADER_MODEL_6_6, true,
  1615. optsBase, _countof(optsBase), values);
  1616. VERIFY_ARE_EQUAL(values[1], (uint32_t)1);
  1617. }
  1618. }
  1619. }
  1620. TEST_F(ExecutionTest, BasicComputeTest) {
  1621. #ifndef _HLK_CONF
  1622. //
  1623. // BasicComputeTest is a simple compute shader that can be used as the basis
  1624. // for more interesting compute execution tests.
  1625. // The HLSL is compatible with shader models <=5.1 to allow using the DXBC
  1626. // rendering code paths for comparison.
  1627. //
  1628. static const char pShader[] =
  1629. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1630. "[numthreads(8,8,1)]\r\n"
  1631. "void main(uint GI : SV_GroupIndex) {"
  1632. " uint addr = GI * 4;\r\n"
  1633. " uint val = g_bab.Load(addr);\r\n"
  1634. " DeviceMemoryBarrierWithGroupSync();\r\n"
  1635. " g_bab.Store(addr, val + 1);\r\n"
  1636. "}";
  1637. static const int NumThreadsX = 8;
  1638. static const int NumThreadsY = 8;
  1639. static const int NumThreadsZ = 1;
  1640. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1641. static const int DispatchGroupCount = 1;
  1642. CComPtr<ID3D12Device> pDevice;
  1643. if (!CreateDevice(&pDevice))
  1644. return;
  1645. std::vector<uint32_t> values;
  1646. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1647. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1648. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1649. VERIFY_ARE_EQUAL(values[0], (uint32_t)1);
  1650. #endif
  1651. }
  1652. TEST_F(ExecutionTest, BasicTriangleTest) {
  1653. #ifndef _HLK_CONF
  1654. static const UINT FrameCount = 2;
  1655. static const UINT m_width = 320;
  1656. static const UINT m_height = 200;
  1657. static const float m_aspectRatio = static_cast<float>(m_width) / static_cast<float>(m_height);
  1658. struct Vertex {
  1659. XMFLOAT3 position;
  1660. XMFLOAT4 color;
  1661. };
  1662. // Pipeline objects.
  1663. CComPtr<ID3D12Device> pDevice;
  1664. CComPtr<ID3D12Resource> pRenderTarget;
  1665. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1666. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1667. CComPtr<ID3D12RootSignature> pRootSig;
  1668. CComPtr<ID3D12DescriptorHeap> pRtvHeap;
  1669. CComPtr<ID3D12PipelineState> pPipelineState;
  1670. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1671. CComPtr<ID3D12Resource> pReadBuffer;
  1672. UINT rtvDescriptorSize;
  1673. CComPtr<ID3D12Resource> pVertexBuffer;
  1674. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  1675. // Synchronization objects.
  1676. FenceObj FO;
  1677. // Shaders.
  1678. static const char pShaders[] =
  1679. "struct PSInput {\r\n"
  1680. " float4 position : SV_POSITION;\r\n"
  1681. " float4 color : COLOR;\r\n"
  1682. "};\r\n\r\n"
  1683. "PSInput VSMain(float4 position : POSITION, float4 color : COLOR) {\r\n"
  1684. " PSInput result;\r\n"
  1685. "\r\n"
  1686. " result.position = position;\r\n"
  1687. " result.color = color;\r\n"
  1688. " return result;\r\n"
  1689. "}\r\n\r\n"
  1690. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  1691. " return 1; //input.color;\r\n"
  1692. "};\r\n";
  1693. if (!CreateDevice(&pDevice))
  1694. return;
  1695. struct BasicTestChecker {
  1696. CComPtr<ID3D12Device> m_pDevice;
  1697. CComPtr<ID3D12InfoQueue> m_pInfoQueue;
  1698. bool m_OK = false;
  1699. void SetOK(bool value) { m_OK = value; }
  1700. BasicTestChecker(ID3D12Device *pDevice) : m_pDevice(pDevice) {
  1701. if (FAILED(m_pDevice.QueryInterface(&m_pInfoQueue)))
  1702. return;
  1703. m_pInfoQueue->PushEmptyStorageFilter();
  1704. m_pInfoQueue->PushEmptyRetrievalFilter();
  1705. }
  1706. ~BasicTestChecker() {
  1707. if (!m_OK && m_pInfoQueue != nullptr) {
  1708. UINT64 count = m_pInfoQueue->GetNumStoredMessages();
  1709. bool invalidBytecodeFound = false;
  1710. CAtlArray<BYTE> m_pBytes;
  1711. for (UINT64 i = 0; i < count; ++i) {
  1712. SIZE_T len = 0;
  1713. if (FAILED(m_pInfoQueue->GetMessageA(i, nullptr, &len)))
  1714. continue;
  1715. if (m_pBytes.GetCount() < len && !m_pBytes.SetCount(len))
  1716. continue;
  1717. D3D12_MESSAGE *pMsg = (D3D12_MESSAGE *)m_pBytes.GetData();
  1718. if (FAILED(m_pInfoQueue->GetMessageA(i, pMsg, &len)))
  1719. continue;
  1720. if (pMsg->ID == D3D12_MESSAGE_ID_CREATEVERTEXSHADER_INVALIDSHADERBYTECODE ||
  1721. pMsg->ID == D3D12_MESSAGE_ID_CREATEPIXELSHADER_INVALIDSHADERBYTECODE) {
  1722. invalidBytecodeFound = true;
  1723. break;
  1724. }
  1725. }
  1726. if (invalidBytecodeFound) {
  1727. LogCommentFmt(L"%s", L"Found an invalid bytecode message. This "
  1728. L"typically indicates that experimental mode "
  1729. L"is not set up properly.");
  1730. if (!GetTestParamBool(L"ExperimentalShaders")) {
  1731. LogCommentFmt(L"Note that the ExperimentalShaders test parameter isn't set.");
  1732. }
  1733. }
  1734. else {
  1735. LogCommentFmt(L"Did not find corrupt pixel or vertex shaders in "
  1736. L"queue - dumping complete queue.");
  1737. WriteInfoQueueMessages(nullptr, OutputFn, m_pInfoQueue);
  1738. }
  1739. }
  1740. }
  1741. static void __stdcall OutputFn(void *pCtx, const wchar_t *pMsg) {
  1742. UNREFERENCED_PARAMETER(pCtx);
  1743. LogCommentFmt(L"%s", pMsg);
  1744. }
  1745. };
  1746. BasicTestChecker BTC(pDevice);
  1747. {
  1748. InitFenceObj(pDevice, &FO);
  1749. CreateRtvDescriptorHeap(pDevice, FrameCount, &pRtvHeap, &rtvDescriptorSize);
  1750. CreateRenderTargetAndReadback(pDevice, pRtvHeap, m_width, m_height, &pRenderTarget, &pReadBuffer);
  1751. // Create an empty root signature.
  1752. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  1753. rootSignatureDesc.Init(
  1754. 0, nullptr, 0, nullptr,
  1755. D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  1756. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSig);
  1757. // Create the pipeline state, which includes compiling and loading shaders.
  1758. // Define the vertex input layout.
  1759. D3D12_INPUT_ELEMENT_DESC inputElementDescs[] = {
  1760. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  1761. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
  1762. {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12,
  1763. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  1764. D3D12_INPUT_LAYOUT_DESC InputLayout = { inputElementDescs, _countof(inputElementDescs) };
  1765. CreateGraphicsPSO(pDevice, &InputLayout, pRootSig, pShaders, &pPipelineState);
  1766. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue,
  1767. &pCommandAllocator, &pCommandList,
  1768. pPipelineState);
  1769. // Define the geometry for a triangle.
  1770. Vertex triangleVertices[] = {
  1771. { { 0.0f, 0.25f * m_aspectRatio, 0.0f },{ 1.0f, 0.0f, 0.0f, 1.0f } },
  1772. { { 0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 1.0f, 0.0f, 1.0f } },
  1773. { { -0.25f, -0.25f * m_aspectRatio, 0.0f },{ 0.0f, 0.0f, 1.0f, 1.0f } } };
  1774. CreateVertexBuffer(pDevice, triangleVertices, &pVertexBuffer, &vertexBufferView);
  1775. WaitForSignal(pCommandQueue, FO);
  1776. }
  1777. // Render and execute the command list.
  1778. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, 1,
  1779. &vertexBufferView, pRootSig, pRenderTarget,
  1780. pReadBuffer);
  1781. VERIFY_SUCCEEDED(pCommandList->Close());
  1782. ExecuteCommandList(pCommandQueue, pCommandList);
  1783. // Wait for previous frame.
  1784. WaitForSignal(pCommandQueue, FO);
  1785. // At this point, we've verified that execution succeeded with DXIL.
  1786. BTC.SetOK(true);
  1787. // Read back to CPU and examine contents.
  1788. {
  1789. MappedData data(pReadBuffer, m_width * m_height * 4);
  1790. const uint32_t *pPixels = (uint32_t *)data.data();
  1791. if (SaveImages()) {
  1792. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, m_width, m_height, L"basic.bmp");
  1793. }
  1794. uint32_t top = pPixels[m_width / 2]; // Top center.
  1795. uint32_t mid = pPixels[m_width / 2 + m_width * (m_height / 2)]; // Middle center.
  1796. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  1797. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  1798. }
  1799. #endif
  1800. }
  1801. TEST_F(ExecutionTest, Int64Test) {
  1802. static const char pShader[] =
  1803. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1804. "[numthreads(8,8,1)]\r\n"
  1805. "void main(uint GI : SV_GroupIndex) {"
  1806. " uint addr = GI * 4;\r\n"
  1807. " uint val = g_bab.Load(addr);\r\n"
  1808. " uint64_t u64 = val;\r\n"
  1809. " u64 *= val;\r\n"
  1810. " g_bab.Store(addr, (uint)(u64 >> 32));\r\n"
  1811. "}";
  1812. static const int NumThreadsX = 8;
  1813. static const int NumThreadsY = 8;
  1814. static const int NumThreadsZ = 1;
  1815. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1816. static const int DispatchGroupCount = 1;
  1817. CComPtr<ID3D12Device> pDevice;
  1818. if (!CreateDevice(&pDevice))
  1819. return;
  1820. if (!DoesDeviceSupportInt64(pDevice)) {
  1821. // Optional feature, so it's correct to not support it if declared as such.
  1822. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  1823. return;
  1824. }
  1825. std::vector<uint32_t> values;
  1826. SetupComputeValuePattern(values, ThreadsPerGroup * DispatchGroupCount);
  1827. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1828. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1829. VERIFY_ARE_EQUAL(values[0], (uint32_t)0);
  1830. }
  1831. TEST_F(ExecutionTest, SignTest) {
  1832. static const char pShader[] =
  1833. "RWByteAddressBuffer g_bab : register(u0);\r\n"
  1834. "[numthreads(8,1,1)]\r\n"
  1835. "void main(uint GI : SV_GroupIndex) {"
  1836. " uint addr = GI * 4;\r\n"
  1837. " int val = g_bab.Load(addr);\r\n"
  1838. " g_bab.Store(addr, (uint)(sign(val)));\r\n"
  1839. "}";
  1840. static const int NumThreadsX = 8;
  1841. static const int NumThreadsY = 1;
  1842. static const int NumThreadsZ = 1;
  1843. static const int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  1844. static const int DispatchGroupCount = 1;
  1845. CComPtr<ID3D12Device> pDevice;
  1846. if (!CreateDevice(&pDevice))
  1847. return;
  1848. const uint32_t neg1 = (uint32_t)-1;
  1849. uint32_t origValues[] = { (uint32_t)-3, (uint32_t)-2, neg1, 0, 1, 2, 3, 4 };
  1850. std::vector<uint32_t> values(origValues, origValues + _countof(origValues));
  1851. RunRWByteBufferComputeTest(pDevice, pShader, values);
  1852. VERIFY_ARE_EQUAL(values[0], neg1);
  1853. VERIFY_ARE_EQUAL(values[1], neg1);
  1854. VERIFY_ARE_EQUAL(values[2], neg1);
  1855. VERIFY_ARE_EQUAL(values[3], (uint32_t)0);
  1856. VERIFY_ARE_EQUAL(values[4], (uint32_t)1);
  1857. VERIFY_ARE_EQUAL(values[5], (uint32_t)1);
  1858. VERIFY_ARE_EQUAL(values[6], (uint32_t)1);
  1859. VERIFY_ARE_EQUAL(values[7], (uint32_t)1);
  1860. }
  1861. TEST_F(ExecutionTest, WaveIntrinsicsDDITest) {
  1862. #ifndef _HLK_CONF
  1863. CComPtr<ID3D12Device> pDevice;
  1864. if (!CreateDevice(&pDevice))
  1865. return;
  1866. D3D12_FEATURE_DATA_D3D12_OPTIONS1 O;
  1867. if (FAILED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &O, sizeof(O))))
  1868. return;
  1869. bool waveSupported = O.WaveOps;
  1870. UINT laneCountMin = O.WaveLaneCountMin;
  1871. UINT laneCountMax = O.WaveLaneCountMax;
  1872. LogCommentFmt(L"WaveOps %i, WaveLaneCountMin %u, WaveLaneCountMax %u", waveSupported, laneCountMin, laneCountMax);
  1873. VERIFY_IS_TRUE(laneCountMin <= laneCountMax);
  1874. if (waveSupported) {
  1875. VERIFY_IS_TRUE(laneCountMin > 0 && laneCountMax > 0);
  1876. }
  1877. else {
  1878. VERIFY_IS_TRUE(laneCountMin == 0 && laneCountMax == 0);
  1879. }
  1880. #endif
  1881. }
  1882. TEST_F(ExecutionTest, WaveIntrinsicsTest) {
  1883. #ifndef _HLK_CONF
  1884. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  1885. struct PerThreadData {
  1886. uint32_t id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;
  1887. uint32_t allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;
  1888. uint32_t pfBC, pfSum, pfProd;
  1889. uint32_t ballot[4];
  1890. uint32_t diver; // divergent value, used in calculation
  1891. int32_t i_diver; // divergent value, used in calculation
  1892. int32_t i_allMax, i_allMin, i_allSum, i_allProd;
  1893. int32_t i_pfSum, i_pfProd;
  1894. };
  1895. static const char pShader[] =
  1896. WAVE_INTRINSIC_DXBC_GUARD
  1897. "struct PerThreadData {\r\n"
  1898. " uint id, flags, laneIndex, laneCount, firstLaneId, preds, firstlaneX, lane1X;\r\n"
  1899. " uint allBC, allSum, allProd, allAND, allOR, allXOR, allMin, allMax;\r\n"
  1900. " uint pfBC, pfSum, pfProd;\r\n"
  1901. " uint4 ballot;\r\n"
  1902. " uint diver;\r\n"
  1903. " int i_diver;\r\n"
  1904. " int i_allMax, i_allMin, i_allSum, i_allProd;\r\n"
  1905. " int i_pfSum, i_pfProd;\r\n"
  1906. "};\r\n"
  1907. "RWStructuredBuffer<PerThreadData> g_sb : register(u0);\r\n"
  1908. "[numthreads(8,8,1)]\r\n"
  1909. "void main(uint GI : SV_GroupIndex, uint3 GTID : SV_GroupThreadID) {"
  1910. " PerThreadData pts = g_sb[GI];\r\n"
  1911. " uint diver = GTID.x + 2;\r\n"
  1912. " pts.diver = diver;\r\n"
  1913. " pts.flags = 0;\r\n"
  1914. " pts.preds = 0;\r\n"
  1915. " if (WaveIsFirstLane()) pts.flags |= 1;\r\n"
  1916. " pts.laneIndex = WaveGetLaneIndex();\r\n"
  1917. " pts.laneCount = WaveGetLaneCount();\r\n"
  1918. " pts.firstLaneId = WaveReadLaneFirst(pts.id);\r\n"
  1919. " pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);\r\n"
  1920. " pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);\r\n"
  1921. " pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);\r\n"
  1922. " pts.preds |= ((WaveActiveAllEqual(GTID.z) ? 1 : 0) << 3);\r\n"
  1923. " pts.preds |= ((WaveActiveAllEqual(WaveReadLaneFirst(diver)) ? 1 : 0) << 4);\r\n"
  1924. " pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  1925. " pts.firstlaneX = WaveReadLaneFirst(GTID.x);\r\n"
  1926. " pts.lane1X = WaveReadLaneAt(GTID.x, 1);\r\n"
  1927. "\r\n"
  1928. " pts.allBC = WaveActiveCountBits(diver > 3);\r\n"
  1929. " pts.allSum = WaveActiveSum(diver);\r\n"
  1930. " pts.allProd = WaveActiveProduct(diver);\r\n"
  1931. " pts.allAND = WaveActiveBitAnd(diver);\r\n"
  1932. " pts.allOR = WaveActiveBitOr(diver);\r\n"
  1933. " pts.allXOR = WaveActiveBitXor(diver);\r\n"
  1934. " pts.allMin = WaveActiveMin(diver);\r\n"
  1935. " pts.allMax = WaveActiveMax(diver);\r\n"
  1936. "\r\n"
  1937. " pts.pfBC = WavePrefixCountBits(diver > 3);\r\n"
  1938. " pts.pfSum = WavePrefixSum(diver);\r\n"
  1939. " pts.pfProd = WavePrefixProduct(diver);\r\n"
  1940. "\r\n"
  1941. " int i_diver = pts.i_diver;\r\n"
  1942. " pts.i_allMax = WaveActiveMax(i_diver);\r\n"
  1943. " pts.i_allMin = WaveActiveMin(i_diver);\r\n"
  1944. " pts.i_allSum = WaveActiveSum(i_diver);\r\n"
  1945. " pts.i_allProd = WaveActiveProduct(i_diver);\r\n"
  1946. " pts.i_pfSum = WavePrefixSum(i_diver);\r\n"
  1947. " pts.i_pfProd = WavePrefixProduct(i_diver);\r\n"
  1948. "\r\n"
  1949. " g_sb[GI] = pts;\r\n"
  1950. "}";
  1951. static const int NumtheadsX = 8;
  1952. static const int NumtheadsY = 8;
  1953. static const int NumtheadsZ = 1;
  1954. static const int ThreadsPerGroup = NumtheadsX * NumtheadsY * NumtheadsZ;
  1955. static const int DispatchGroupCount = 1;
  1956. CComPtr<ID3D12Device> pDevice;
  1957. if (!CreateDevice(&pDevice))
  1958. return;
  1959. if (!DoesDeviceSupportWaveOps(pDevice)) {
  1960. // Optional feature, so it's correct to not support it if declared as such.
  1961. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  1962. return;
  1963. }
  1964. std::vector<PerThreadData> values;
  1965. values.resize(ThreadsPerGroup * DispatchGroupCount);
  1966. for (size_t i = 0; i < values.size(); ++i) {
  1967. memset(&values[i], 0, sizeof(PerThreadData));
  1968. values[i].id = (uint32_t)i;
  1969. values[i].i_diver = (int)i;
  1970. values[i].i_diver *= (i % 2) ? 1 : -1;
  1971. }
  1972. static const int DispatchGroupX = 1;
  1973. static const int DispatchGroupY = 1;
  1974. static const int DispatchGroupZ = 1;
  1975. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  1976. CComPtr<ID3D12CommandQueue> pCommandQueue;
  1977. CComPtr<ID3D12DescriptorHeap> pUavHeap;
  1978. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  1979. UINT uavDescriptorSize;
  1980. FenceObj FO;
  1981. bool dxbc = UseDxbc();
  1982. const size_t valueSizeInBytes = values.size() * sizeof(PerThreadData);
  1983. CreateComputeCommandQueue(pDevice, L"WaveIntrinsicsTest Command Queue", &pCommandQueue);
  1984. InitFenceObj(pDevice, &FO);
  1985. // Describe and create a UAV descriptor heap.
  1986. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  1987. heapDesc.NumDescriptors = 1;
  1988. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  1989. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  1990. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  1991. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  1992. // Create root signature.
  1993. CComPtr<ID3D12RootSignature> pRootSignature;
  1994. {
  1995. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  1996. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 0, 0, 0);
  1997. CD3DX12_ROOT_PARAMETER rootParameters[1];
  1998. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  1999. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2000. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE);
  2001. CComPtr<ID3DBlob> signature;
  2002. CComPtr<ID3DBlob> error;
  2003. VERIFY_SUCCEEDED(D3D12SerializeRootSignature(&rootSignatureDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
  2004. VERIFY_SUCCEEDED(pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&pRootSignature)));
  2005. }
  2006. // Create pipeline state object.
  2007. CComPtr<ID3D12PipelineState> pComputeState;
  2008. CreateComputePSO(pDevice, pRootSignature, pShader, L"cs_6_0", &pComputeState);
  2009. // Create a command allocator and list for compute.
  2010. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  2011. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  2012. // Set up UAV resource.
  2013. CComPtr<ID3D12Resource> pUavResource;
  2014. CComPtr<ID3D12Resource> pReadBuffer;
  2015. CComPtr<ID3D12Resource> pUploadResource;
  2016. CreateTestUavs(pDevice, pCommandList, values.data(), (UINT)valueSizeInBytes, &pUavResource, &pUploadResource, &pReadBuffer);
  2017. // Close the command list and execute it to perform the GPU setup.
  2018. pCommandList->Close();
  2019. ExecuteCommandList(pCommandQueue, pCommandList);
  2020. WaitForSignal(pCommandQueue, FO);
  2021. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  2022. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  2023. // Run the compute shader and copy the results back to readable memory.
  2024. {
  2025. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  2026. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  2027. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  2028. uavDesc.Buffer.FirstElement = 0;
  2029. uavDesc.Buffer.NumElements = (UINT)values.size();
  2030. uavDesc.Buffer.StructureByteStride = sizeof(PerThreadData);
  2031. uavDesc.Buffer.CounterOffsetInBytes = 0;
  2032. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  2033. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  2034. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  2035. pDevice->CreateUnorderedAccessView(pUavResource, nullptr, &uavDesc, uavHandle);
  2036. SetDescriptorHeap(pCommandList, pUavHeap);
  2037. pCommandList->SetComputeRootSignature(pRootSignature);
  2038. pCommandList->SetComputeRootDescriptorTable(0, uavHandleGpu);
  2039. }
  2040. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  2041. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2042. pCommandList->CopyResource(pReadBuffer, pUavResource);
  2043. pCommandList->Close();
  2044. ExecuteCommandList(pCommandQueue, pCommandList);
  2045. WaitForSignal(pCommandQueue, FO);
  2046. {
  2047. MappedData mappedData(pReadBuffer, (UINT)valueSizeInBytes);
  2048. PerThreadData *pData = (PerThreadData *)mappedData.data();
  2049. memcpy(values.data(), pData, valueSizeInBytes);
  2050. // Gather some general data.
  2051. // The 'firstLaneId' captures a unique number per first-lane per wave.
  2052. // Counting the number distinct firstLaneIds gives us the number of waves.
  2053. std::vector<uint32_t> firstLaneIds;
  2054. for (size_t i = 0; i < values.size(); ++i) {
  2055. PerThreadData &pts = values[i];
  2056. uint32_t firstLaneId = pts.firstLaneId;
  2057. if (!contains(firstLaneIds, firstLaneId)) {
  2058. firstLaneIds.push_back(firstLaneId);
  2059. }
  2060. }
  2061. // Waves should cover 4 threads or more.
  2062. LogCommentFmt(L"Found %u distinct lane ids: %u", firstLaneIds.size());
  2063. if (!dxbc) {
  2064. VERIFY_IS_GREATER_THAN_OR_EQUAL(values.size() / 4, firstLaneIds.size());
  2065. }
  2066. // Now, group threads into waves.
  2067. std::map<uint32_t, std::unique_ptr<std::vector<PerThreadData *> > > waves;
  2068. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  2069. waves[firstLaneIds[i]] = std::make_unique<std::vector<PerThreadData *> >();
  2070. }
  2071. for (size_t i = 0; i < values.size(); ++i) {
  2072. PerThreadData &pts = values[i];
  2073. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  2074. wave->push_back(&pts);
  2075. }
  2076. // Verify that all the wave values are coherent across the wave.
  2077. for (size_t i = 0; i < values.size(); ++i) {
  2078. PerThreadData &pts = values[i];
  2079. std::unique_ptr<std::vector<PerThreadData *> > &wave = waves[pts.firstLaneId];
  2080. // Sort the lanes by increasing lane ID.
  2081. struct LaneIdOrderPred {
  2082. bool operator()(PerThreadData *a, PerThreadData *b) {
  2083. return a->laneIndex < b->laneIndex;
  2084. }
  2085. };
  2086. std::sort(wave.get()->begin(), wave.get()->end(), LaneIdOrderPred());
  2087. // Verify some interesting properties of the first lane.
  2088. uint32_t pfBC, pfSum, pfProd;
  2089. int32_t i_pfSum, i_pfProd;
  2090. int32_t i_allMax, i_allMin;
  2091. {
  2092. PerThreadData *ptdFirst = wave->front();
  2093. VERIFY_IS_TRUE(0 != (ptdFirst->flags & 1)); // FirstLane sets this bit.
  2094. VERIFY_IS_TRUE(0 == ptdFirst->pfBC);
  2095. VERIFY_IS_TRUE(0 == ptdFirst->pfSum);
  2096. VERIFY_IS_TRUE(1 == ptdFirst->pfProd);
  2097. VERIFY_IS_TRUE(0 == ptdFirst->i_pfSum);
  2098. VERIFY_IS_TRUE(1 == ptdFirst->i_pfProd);
  2099. pfBC = (ptdFirst->diver > 3) ? 1 : 0;
  2100. pfSum = ptdFirst->diver;
  2101. pfProd = ptdFirst->diver;
  2102. i_pfSum = ptdFirst->i_diver;
  2103. i_pfProd = ptdFirst->i_diver;
  2104. i_allMax = i_allMin = ptdFirst->i_diver;
  2105. }
  2106. // Calculate values which take into consideration all lanes.
  2107. uint32_t preds = 0;
  2108. preds |= 1 << 1; // AllTrue starts true, switches to false if needed.
  2109. preds |= 1 << 2; // AllEqual starts true, switches to false if needed.
  2110. preds |= 1 << 3; // WaveActiveAllEqual(GTID.z) is always true
  2111. preds |= 1 << 4; // (WaveActiveAllEqual(WaveReadLaneFirst(diver)) is always true
  2112. uint32_t ballot[4] = { 0, 0, 0, 0 };
  2113. int32_t i_allSum = 0, i_allProd = 1;
  2114. for (size_t n = 0; n < wave->size(); ++n) {
  2115. std::vector<PerThreadData *> &lanes = *wave.get();
  2116. // pts.preds |= ((WaveActiveAnyTrue(diver == 1) ? 1 : 0) << 0);
  2117. if (lanes[n]->diver == 1) preds |= (1 << 0);
  2118. // pts.preds |= ((WaveActiveAllTrue(diver == 1) ? 1 : 0) << 1);
  2119. if (lanes[n]->diver != 1) preds &= ~(1 << 1);
  2120. // pts.preds |= ((WaveActiveAllEqual(diver) ? 1 : 0) << 2);
  2121. if (lanes[0]->diver != lanes[n]->diver) preds &= ~(1 << 2);
  2122. // pts.ballot = WaveActiveBallot(diver > 3);\r\n"
  2123. if (lanes[n]->diver > 3) {
  2124. // This is the uint4 result layout:
  2125. // .x -> bits 0 .. 31
  2126. // .y -> bits 32 .. 63
  2127. // .z -> bits 64 .. 95
  2128. // .w -> bits 96 ..127
  2129. uint32_t component = lanes[n]->laneIndex / 32;
  2130. uint32_t bit = lanes[n]->laneIndex % 32;
  2131. ballot[component] |= 1 << bit;
  2132. }
  2133. i_allMax = std::max(lanes[n]->i_diver, i_allMax);
  2134. i_allMin = std::min(lanes[n]->i_diver, i_allMin);
  2135. i_allProd *= lanes[n]->i_diver;
  2136. i_allSum += lanes[n]->i_diver;
  2137. }
  2138. for (size_t n = 1; n < wave->size(); ++n) {
  2139. // 'All' operations are uniform across the wave.
  2140. std::vector<PerThreadData *> &lanes = *wave.get();
  2141. VERIFY_IS_TRUE(0 == (lanes[n]->flags & 1)); // non-firstlanes do not set this bit
  2142. VERIFY_ARE_EQUAL(lanes[0]->allBC, lanes[n]->allBC);
  2143. VERIFY_ARE_EQUAL(lanes[0]->allSum, lanes[n]->allSum);
  2144. VERIFY_ARE_EQUAL(lanes[0]->allProd, lanes[n]->allProd);
  2145. VERIFY_ARE_EQUAL(lanes[0]->allAND, lanes[n]->allAND);
  2146. VERIFY_ARE_EQUAL(lanes[0]->allOR, lanes[n]->allOR);
  2147. VERIFY_ARE_EQUAL(lanes[0]->allXOR, lanes[n]->allXOR);
  2148. VERIFY_ARE_EQUAL(lanes[0]->allMin, lanes[n]->allMin);
  2149. VERIFY_ARE_EQUAL(lanes[0]->allMax, lanes[n]->allMax);
  2150. VERIFY_ARE_EQUAL(i_allMax, lanes[n]->i_allMax);
  2151. VERIFY_ARE_EQUAL(i_allMin, lanes[n]->i_allMin);
  2152. VERIFY_ARE_EQUAL(i_allProd, lanes[n]->i_allProd);
  2153. VERIFY_ARE_EQUAL(i_allSum, lanes[n]->i_allSum);
  2154. // first-lane reads and uniform reads are uniform across the wave.
  2155. VERIFY_ARE_EQUAL(lanes[0]->firstlaneX, lanes[n]->firstlaneX);
  2156. VERIFY_ARE_EQUAL(lanes[0]->lane1X, lanes[n]->lane1X);
  2157. // the lane count is uniform across the wave.
  2158. VERIFY_ARE_EQUAL(lanes[0]->laneCount, lanes[n]->laneCount);
  2159. // The predicates are uniform across the wave.
  2160. VERIFY_ARE_EQUAL(lanes[n]->preds, preds);
  2161. // the lane index is distinct per thread.
  2162. for (size_t prior = 0; prior < n; ++prior) {
  2163. VERIFY_ARE_NOT_EQUAL(lanes[prior]->laneIndex, lanes[n]->laneIndex);
  2164. }
  2165. // Ballot results are uniform across the wave.
  2166. VERIFY_ARE_EQUAL(0, memcmp(ballot, lanes[n]->ballot, sizeof(ballot)));
  2167. // Keep running total of prefix calculation. Prefix values are exclusive to
  2168. // the executing lane.
  2169. VERIFY_ARE_EQUAL(pfBC, lanes[n]->pfBC);
  2170. VERIFY_ARE_EQUAL(pfSum, lanes[n]->pfSum);
  2171. VERIFY_ARE_EQUAL(pfProd, lanes[n]->pfProd);
  2172. VERIFY_ARE_EQUAL(i_pfSum, lanes[n]->i_pfSum);
  2173. VERIFY_ARE_EQUAL(i_pfProd, lanes[n]->i_pfProd);
  2174. pfBC += (lanes[n]->diver > 3) ? 1 : 0;
  2175. pfSum += lanes[n]->diver;
  2176. pfProd *= lanes[n]->diver;
  2177. i_pfSum += lanes[n]->i_diver;
  2178. i_pfProd *= lanes[n]->i_diver;
  2179. }
  2180. // TODO: add divergent branching and verify that the otherwise uniform values properly diverge
  2181. }
  2182. // Compare each value of each per-thread element.
  2183. for (size_t i = 0; i < values.size(); ++i) {
  2184. PerThreadData &pts = values[i];
  2185. VERIFY_ARE_EQUAL(i, pts.id); // ID is unchanged.
  2186. }
  2187. }
  2188. #endif
  2189. }
  2190. // This test is assuming that the adapter implements WaveReadLaneFirst correctly
  2191. TEST_F(ExecutionTest, WaveIntrinsicsInPSTest) {
  2192. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2193. struct Vertex {
  2194. XMFLOAT3 position;
  2195. };
  2196. struct PerPixelData {
  2197. XMFLOAT4 position;
  2198. uint32_t id, flags, laneIndex, laneCount, firstLaneId, sum1;
  2199. uint32_t id0, id1, id2, id3;
  2200. uint32_t acrossX, acrossY, acrossDiag, quadActiveCount;
  2201. };
  2202. const UINT RTWidth = 128;
  2203. const UINT RTHeight = 128;
  2204. // Shaders.
  2205. static const char pShaders[] =
  2206. WAVE_INTRINSIC_DXBC_GUARD
  2207. "struct PSInput {\r\n"
  2208. " float4 position : SV_POSITION;\r\n"
  2209. "};\r\n\r\n"
  2210. "PSInput VSMain(float4 position : POSITION) {\r\n"
  2211. " PSInput result;\r\n"
  2212. "\r\n"
  2213. " result.position = position;\r\n"
  2214. " return result;\r\n"
  2215. "}\r\n\r\n"
  2216. "uint pos_to_id(float4 pos) { return pos.x * 128 + pos.y; }\r\n"
  2217. "struct PerPixelData {\r\n"
  2218. " float4 position;\r\n"
  2219. " uint id, flags, laneIndex, laneCount, firstLaneId, sum1;\r\n"
  2220. " uint id0, id1, id2, id3;\r\n"
  2221. " uint acrossX, acrossY, acrossDiag, quadActiveCount;\r\n"
  2222. "};\r\n"
  2223. "AppendStructuredBuffer<PerPixelData> g_sb : register(u1);\r\n"
  2224. "float4 PSMain(PSInput input) : SV_TARGET {\r\n"
  2225. " uint one = 1;\r\n"
  2226. " PerPixelData d;\r\n"
  2227. " d.position = input.position;\r\n"
  2228. " d.id = pos_to_id(input.position);\r\n"
  2229. " d.flags = 0;\r\n"
  2230. " if (WaveIsFirstLane()) d.flags |= 1;\r\n"
  2231. " d.laneIndex = WaveGetLaneIndex();\r\n"
  2232. " d.laneCount = WaveGetLaneCount();\r\n"
  2233. " d.firstLaneId = WaveReadLaneFirst(d.id);\r\n"
  2234. " d.sum1 = WaveActiveSum(one);\r\n"
  2235. " d.id0 = QuadReadLaneAt(d.id, 0);\r\n"
  2236. " d.id1 = QuadReadLaneAt(d.id, 1);\r\n"
  2237. " d.id2 = QuadReadLaneAt(d.id, 2);\r\n"
  2238. " d.id3 = QuadReadLaneAt(d.id, 3);\r\n"
  2239. " d.acrossX = QuadReadAcrossX(d.id);\r\n"
  2240. " d.acrossY = QuadReadAcrossY(d.id);\r\n"
  2241. " d.acrossDiag = QuadReadAcrossDiagonal(d.id);\r\n"
  2242. " d.quadActiveCount = one + QuadReadAcrossX(one) + QuadReadAcrossY(one) + QuadReadAcrossDiagonal(one);\r\n"
  2243. " g_sb.Append(d);\r\n"
  2244. " return 1;\r\n"
  2245. "};\r\n";
  2246. CComPtr<ID3D12Device> pDevice;
  2247. CComPtr<ID3D12CommandQueue> pCommandQueue;
  2248. CComPtr<ID3D12DescriptorHeap> pUavHeap, pRtvHeap;
  2249. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  2250. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  2251. CComPtr<ID3D12PipelineState> pPSO;
  2252. CComPtr<ID3D12Resource> pRenderTarget, pReadBuffer;
  2253. UINT uavDescriptorSize, rtvDescriptorSize;
  2254. CComPtr<ID3D12Resource> pVertexBuffer;
  2255. D3D12_VERTEX_BUFFER_VIEW vertexBufferView;
  2256. if (!CreateDevice(&pDevice))
  2257. return;
  2258. if (!DoesDeviceSupportWaveOps(pDevice)) {
  2259. // Optional feature, so it's correct to not support it if declared as such.
  2260. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  2261. return;
  2262. }
  2263. FenceObj FO;
  2264. InitFenceObj(pDevice, &FO);
  2265. // Describe and create a UAV descriptor heap.
  2266. D3D12_DESCRIPTOR_HEAP_DESC heapDesc = {};
  2267. heapDesc.NumDescriptors = 1;
  2268. heapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
  2269. heapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE;
  2270. VERIFY_SUCCEEDED(pDevice->CreateDescriptorHeap(&heapDesc, IID_PPV_ARGS(&pUavHeap)));
  2271. uavDescriptorSize = pDevice->GetDescriptorHandleIncrementSize(heapDesc.Type);
  2272. CreateRtvDescriptorHeap(pDevice, 1, &pRtvHeap, &rtvDescriptorSize);
  2273. CreateRenderTargetAndReadback(pDevice, pRtvHeap, RTHeight, RTWidth, &pRenderTarget, &pReadBuffer);
  2274. // Create root signature: one UAV.
  2275. CComPtr<ID3D12RootSignature> pRootSignature;
  2276. {
  2277. CD3DX12_DESCRIPTOR_RANGE ranges[1];
  2278. ranges[0].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, 1, 0, 0);
  2279. CD3DX12_ROOT_PARAMETER rootParameters[1];
  2280. rootParameters[0].InitAsDescriptorTable(1, &ranges[0], D3D12_SHADER_VISIBILITY_ALL);
  2281. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  2282. rootSignatureDesc.Init(_countof(rootParameters), rootParameters, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
  2283. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  2284. }
  2285. D3D12_INPUT_ELEMENT_DESC elementDesc[] = {
  2286. {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0,
  2287. D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}};
  2288. D3D12_INPUT_LAYOUT_DESC InputLayout = {elementDesc, _countof(elementDesc)};
  2289. CreateGraphicsPSO(pDevice, &InputLayout, pRootSignature, pShaders, &pPSO);
  2290. CreateGraphicsCommandQueueAndList(pDevice, &pCommandQueue, &pCommandAllocator,
  2291. &pCommandList, pPSO);
  2292. // Single triangle covering half the target.
  2293. Vertex vertices[] = {
  2294. { { -1.0f, 1.0f, 0.0f } },
  2295. { { 1.0f, 1.0f, 0.0f } },
  2296. { { -1.0f, -1.0f, 0.0f } } };
  2297. const UINT TriangleCount = _countof(vertices) / 3;
  2298. CreateVertexBuffer(pDevice, vertices, &pVertexBuffer, &vertexBufferView);
  2299. bool dxbc = UseDxbc();
  2300. // Set up UAV resource.
  2301. std::vector<PerPixelData> values;
  2302. values.resize(RTWidth * RTHeight * 2);
  2303. UINT valueSizeInBytes = (UINT)values.size() * sizeof(PerPixelData);
  2304. memset(values.data(), 0, valueSizeInBytes);
  2305. CComPtr<ID3D12Resource> pUavResource;
  2306. CComPtr<ID3D12Resource> pUavReadBuffer;
  2307. CComPtr<ID3D12Resource> pUploadResource;
  2308. CreateTestUavs(pDevice, pCommandList, values.data(), valueSizeInBytes, &pUavResource, &pUploadResource, &pUavReadBuffer);
  2309. // Set up the append counter resource.
  2310. CComPtr<ID3D12Resource> pUavCounterResource;
  2311. CComPtr<ID3D12Resource> pReadCounterBuffer;
  2312. CComPtr<ID3D12Resource> pUploadCounterResource;
  2313. BYTE zero[sizeof(UINT)] = { 0 };
  2314. CreateTestUavs(pDevice, pCommandList, zero, sizeof(zero), &pUavCounterResource, &pUploadCounterResource, &pReadCounterBuffer);
  2315. // Close the command list and execute it to perform the GPU setup.
  2316. pCommandList->Close();
  2317. ExecuteCommandList(pCommandQueue, pCommandList);
  2318. WaitForSignal(pCommandQueue, FO);
  2319. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  2320. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pPSO));
  2321. pCommandList->SetGraphicsRootSignature(pRootSignature);
  2322. SetDescriptorHeap(pCommandList, pUavHeap);
  2323. {
  2324. D3D12_UNORDERED_ACCESS_VIEW_DESC uavDesc = {};
  2325. uavDesc.Format = DXGI_FORMAT_UNKNOWN;
  2326. uavDesc.ViewDimension = D3D12_UAV_DIMENSION_BUFFER;
  2327. uavDesc.Buffer.FirstElement = 0;
  2328. uavDesc.Buffer.NumElements = (UINT)values.size();
  2329. uavDesc.Buffer.StructureByteStride = sizeof(PerPixelData);
  2330. uavDesc.Buffer.CounterOffsetInBytes = 0;
  2331. uavDesc.Buffer.Flags = D3D12_BUFFER_UAV_FLAG_NONE;
  2332. CD3DX12_CPU_DESCRIPTOR_HANDLE uavHandle(pUavHeap->GetCPUDescriptorHandleForHeapStart());
  2333. CD3DX12_GPU_DESCRIPTOR_HANDLE uavHandleGpu(pUavHeap->GetGPUDescriptorHandleForHeapStart());
  2334. pDevice->CreateUnorderedAccessView(pUavResource, pUavCounterResource, &uavDesc, uavHandle);
  2335. pCommandList->SetGraphicsRootDescriptorTable(0, uavHandleGpu);
  2336. }
  2337. RecordRenderAndReadback(pCommandList, pRtvHeap, rtvDescriptorSize, TriangleCount, &vertexBufferView, nullptr, pRenderTarget, pReadBuffer);
  2338. RecordTransitionBarrier(pCommandList, pUavResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2339. RecordTransitionBarrier(pCommandList, pUavCounterResource, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  2340. pCommandList->CopyResource(pUavReadBuffer, pUavResource);
  2341. pCommandList->CopyResource(pReadCounterBuffer, pUavCounterResource);
  2342. VERIFY_SUCCEEDED(pCommandList->Close());
  2343. LogCommentFmt(L"Rendering to %u by %u", RTWidth, RTHeight);
  2344. ExecuteCommandList(pCommandQueue, pCommandList);
  2345. WaitForSignal(pCommandQueue, FO);
  2346. {
  2347. MappedData data(pReadBuffer, RTWidth * RTHeight * 4);
  2348. const uint32_t *pPixels = (uint32_t *)data.data();
  2349. if (SaveImages()) {
  2350. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, RTWidth, RTHeight, L"psintrin.bmp");
  2351. }
  2352. }
  2353. uint32_t appendCount;
  2354. {
  2355. MappedData mappedData(pReadCounterBuffer, sizeof(uint32_t));
  2356. appendCount = *((uint32_t *)mappedData.data());
  2357. LogCommentFmt(L"%u elements in append buffer", appendCount);
  2358. }
  2359. {
  2360. MappedData mappedData(pUavReadBuffer, (UINT32)values.size());
  2361. PerPixelData *pData = (PerPixelData *)mappedData.data();
  2362. memcpy(values.data(), pData, valueSizeInBytes);
  2363. // DXBC is handy to test pipeline setup, but interesting functions are
  2364. // stubbed out, so there is no point in further validation.
  2365. if (dxbc)
  2366. return;
  2367. uint32_t maxActiveLaneCount = 0;
  2368. uint32_t maxLaneCount = 0;
  2369. for (uint32_t i = 0; i < appendCount; ++i) {
  2370. maxActiveLaneCount = std::max(maxActiveLaneCount, values[i].sum1);
  2371. maxLaneCount = std::max(maxLaneCount, values[i].laneCount);
  2372. }
  2373. uint32_t peerOfHelperLanes = 0;
  2374. for (uint32_t i = 0; i < appendCount; ++i) {
  2375. if (values[i].sum1 != maxActiveLaneCount) {
  2376. ++peerOfHelperLanes;
  2377. }
  2378. }
  2379. LogCommentFmt(
  2380. L"Found: %u threads. Waves reported up to %u total lanes, up "
  2381. L"to %u active lanes, and %u threads had helper/inactive lanes.",
  2382. appendCount, maxLaneCount, maxActiveLaneCount, peerOfHelperLanes);
  2383. // Group threads into quad invocations.
  2384. uint32_t singlePixelCount = 0;
  2385. uint32_t multiPixelCount = 0;
  2386. std::unordered_set<uint32_t> ids;
  2387. std::multimap<uint32_t, PerPixelData *> idGroups;
  2388. std::multimap<uint32_t, PerPixelData *> firstIdGroups;
  2389. for (uint32_t i = 0; i < appendCount; ++i) {
  2390. ids.insert(values[i].id);
  2391. idGroups.insert(std::make_pair(values[i].id, &values[i]));
  2392. firstIdGroups.insert(std::make_pair(values[i].firstLaneId, &values[i]));
  2393. }
  2394. for (uint32_t id : ids) {
  2395. if (idGroups.count(id) == 1)
  2396. ++singlePixelCount;
  2397. else
  2398. ++multiPixelCount;
  2399. }
  2400. LogCommentFmt(L"%u pixels were processed by a single thread. %u invocations were for shared pixels.",
  2401. singlePixelCount, multiPixelCount);
  2402. // Multiple threads may have tried to shade the same pixel. (Is this true even if we have only one triangle?)
  2403. // Where every pixel is distinct, it's very straightforward to validate.
  2404. {
  2405. auto cur = firstIdGroups.begin(), end = firstIdGroups.end();
  2406. while (cur != end) {
  2407. bool simpleWave = true;
  2408. uint32_t firstId = (*cur).first;
  2409. auto groupEnd = cur;
  2410. while (groupEnd != end && (*groupEnd).first == firstId) {
  2411. if (idGroups.count((*groupEnd).second->id) > 1)
  2412. simpleWave = false;
  2413. ++groupEnd;
  2414. }
  2415. if (simpleWave) {
  2416. // Break the wave into quads.
  2417. struct QuadData {
  2418. unsigned count;
  2419. PerPixelData *data[4];
  2420. };
  2421. std::map<uint32_t, QuadData> quads;
  2422. for (auto i = cur; i != groupEnd; ++i) {
  2423. // assuming that it is a simple wave, idGroups has a unique id for each entry.
  2424. uint32_t laneId = (*i).second->id;
  2425. uint32_t laneIds[4] = {(*i).second->id0, (*i).second->id1,
  2426. (*i).second->id2, (*i).second->id3};
  2427. // Since this is a simple wave, each lane has an unique id and
  2428. // therefore should not have any ids in there.
  2429. VERIFY_IS_TRUE(quads.find(laneId) == quads.end());
  2430. // check if QuadReadLaneAt is returning same values in a single quad.
  2431. bool newQuad = true;
  2432. for (unsigned quadIndex = 0; quadIndex < 4; ++quadIndex) {
  2433. auto match = quads.find(laneIds[quadIndex]);
  2434. if (match != quads.end()) {
  2435. (*match).second.data[(*match).second.count++] = (*i).second;
  2436. newQuad = false;
  2437. break;
  2438. }
  2439. auto quadMemberData = idGroups.find(laneIds[quadIndex]);
  2440. if (quadMemberData != idGroups.end()) {
  2441. VERIFY_IS_TRUE((*quadMemberData).second->id0 == laneIds[0]);
  2442. VERIFY_IS_TRUE((*quadMemberData).second->id1 == laneIds[1]);
  2443. VERIFY_IS_TRUE((*quadMemberData).second->id2 == laneIds[2]);
  2444. VERIFY_IS_TRUE((*quadMemberData).second->id3 == laneIds[3]);
  2445. }
  2446. }
  2447. if (newQuad) {
  2448. QuadData qdata;
  2449. qdata.count = 1;
  2450. qdata.data[0] = (*i).second;
  2451. quads.insert(std::make_pair(laneId, qdata));
  2452. }
  2453. }
  2454. for (auto quadPair : quads) {
  2455. unsigned count = quadPair.second.count;
  2456. // There could be only one pixel data on the edge of the triangle
  2457. if (count < 2) continue;
  2458. PerPixelData **data = quadPair.second.data;
  2459. bool isTop[4];
  2460. bool isLeft[4];
  2461. PerPixelData helperData;
  2462. memset(&helperData, sizeof(helperData), 0);
  2463. PerPixelData *layout[4]; // tl,tr,bl,br
  2464. memset(layout, sizeof(layout), 0);
  2465. auto fnToLayout = [&](bool top, bool left) -> PerPixelData ** {
  2466. int idx = top ? 0 : 2;
  2467. idx += left ? 0 : 1;
  2468. return &layout[idx];
  2469. };
  2470. auto fnToLayoutData = [&](bool top, bool left) -> PerPixelData * {
  2471. PerPixelData **pResult = fnToLayout(top, left);
  2472. if (*pResult == nullptr) return &helperData;
  2473. return *pResult;
  2474. };
  2475. VERIFY_IS_TRUE(count <= 4);
  2476. if (count == 2) {
  2477. isTop[0] = data[0]->position.y < data[1]->position.y;
  2478. isTop[1] = (data[0]->position.y == data[1]->position.y) ? isTop[0] : !isTop[0];
  2479. isLeft[0] = data[0]->position.x < data[1]->position.x;
  2480. isLeft[1] = (data[0]->position.x == data[1]->position.x) ? isLeft[0] : !isLeft[0];
  2481. }
  2482. else {
  2483. // with at least three samples, we have distinct x and y coordinates.
  2484. float left = std::min(data[0]->position.x, data[1]->position.x);
  2485. left = std::min(data[2]->position.x, left);
  2486. float top = std::min(data[0]->position.y, data[1]->position.y);
  2487. top = std::min(data[2]->position.y, top);
  2488. for (unsigned i = 0; i < count; ++i) {
  2489. isTop[i] = data[i]->position.y == top;
  2490. isLeft[i] = data[i]->position.x == left;
  2491. }
  2492. }
  2493. for (unsigned i = 0; i < count; ++i) {
  2494. *(fnToLayout(isTop[i], isLeft[i])) = data[i];
  2495. }
  2496. // Finally, we have a proper quad reconstructed. Validate.
  2497. for (unsigned i = 0; i < count; ++i) {
  2498. PerPixelData *d = data[i];
  2499. VERIFY_ARE_EQUAL(d->id0, fnToLayoutData(true, true)->id);
  2500. VERIFY_ARE_EQUAL(d->id1, fnToLayoutData(true, false)->id);
  2501. VERIFY_ARE_EQUAL(d->id2, fnToLayoutData(false, true)->id);
  2502. VERIFY_ARE_EQUAL(d->id3, fnToLayoutData(false, false)->id);
  2503. VERIFY_ARE_EQUAL(d->acrossX, fnToLayoutData(isTop[i], !isLeft[i])->id);
  2504. VERIFY_ARE_EQUAL(d->acrossY, fnToLayoutData(!isTop[i], isLeft[i])->id);
  2505. VERIFY_ARE_EQUAL(d->acrossDiag, fnToLayoutData(!isTop[i], !isLeft[i])->id);
  2506. VERIFY_ARE_EQUAL(d->quadActiveCount, count);
  2507. }
  2508. }
  2509. }
  2510. cur = groupEnd;
  2511. }
  2512. }
  2513. // TODO: provide validation for quads where the same pixel was shaded multiple times
  2514. //
  2515. // Consider: for pixels that were shaded multiple times, check whether
  2516. // some grouping of threads into quads satisfies all value requirements.
  2517. }
  2518. }
  2519. struct ShaderOpTestResult {
  2520. st::ShaderOp *ShaderOp;
  2521. std::shared_ptr<st::ShaderOpSet> ShaderOpSet;
  2522. std::shared_ptr<st::ShaderOpTest> Test;
  2523. };
  2524. struct SPrimitives {
  2525. float f_float;
  2526. float f_float2;
  2527. float f_float_o;
  2528. float f_float2_o;
  2529. };
  2530. std::shared_ptr<ShaderOpTestResult>
  2531. RunShaderOpTestAfterParse(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2532. LPCSTR pName,
  2533. st::ShaderOpTest::TInitCallbackFn pInitCallback,
  2534. std::shared_ptr<st::ShaderOpSet> ShaderOpSet) {
  2535. st::ShaderOp *pShaderOp;
  2536. if (pName == nullptr) {
  2537. if (ShaderOpSet->ShaderOps.size() != 1) {
  2538. VERIFY_FAIL(L"Expected a single shader operation.");
  2539. }
  2540. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  2541. }
  2542. else {
  2543. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  2544. }
  2545. if (pShaderOp == nullptr) {
  2546. std::string msg = "Unable to find shader op ";
  2547. msg += pName;
  2548. msg += "; available ops";
  2549. const char sep = ':';
  2550. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  2551. msg += sep;
  2552. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  2553. }
  2554. CA2W msgWide(msg.c_str());
  2555. VERIFY_FAIL(msgWide.m_psz);
  2556. }
  2557. // This won't actually be used since we're supplying the device,
  2558. // but let's make it consistent.
  2559. pShaderOp->UseWarpDevice = GetTestParamUseWARP(true);
  2560. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  2561. test->SetDxcSupport(&support);
  2562. test->SetInitCallback(pInitCallback);
  2563. test->SetDevice(pDevice);
  2564. test->RunShaderOp(pShaderOp);
  2565. std::shared_ptr<ShaderOpTestResult> result =
  2566. std::make_shared<ShaderOpTestResult>();
  2567. result->ShaderOpSet = ShaderOpSet;
  2568. result->Test = test;
  2569. result->ShaderOp = pShaderOp;
  2570. return result;
  2571. }
  2572. std::shared_ptr<ShaderOpTestResult>
  2573. RunShaderOpTest(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2574. IStream *pStream, LPCSTR pName,
  2575. st::ShaderOpTest::TInitCallbackFn pInitCallback) {
  2576. DXASSERT_NOMSG(pStream != nullptr);
  2577. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2578. std::make_shared<st::ShaderOpSet>();
  2579. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2580. return RunShaderOpTestAfterParse(pDevice, support, pName, pInitCallback, ShaderOpSet);
  2581. }
  2582. TEST_F(ExecutionTest, OutOfBoundsTest) {
  2583. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2584. CComPtr<IStream> pStream;
  2585. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2586. // Single operation test at the moment.
  2587. CComPtr<ID3D12Device> pDevice;
  2588. if (!CreateDevice(&pDevice))
  2589. return;
  2590. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "OOB", nullptr);
  2591. MappedData data;
  2592. // Read back to CPU and examine contents - should get pure red.
  2593. {
  2594. MappedData data;
  2595. test->Test->GetReadBackData("RTarget", &data);
  2596. const uint32_t *pPixels = (uint32_t *)data.data();
  2597. uint32_t first = *pPixels;
  2598. VERIFY_ARE_EQUAL(0xff0000ff, first); // pure red - only first component is read
  2599. }
  2600. }
  2601. TEST_F(ExecutionTest, SaturateTest) {
  2602. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2603. CComPtr<IStream> pStream;
  2604. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2605. // Single operation test at the moment.
  2606. CComPtr<ID3D12Device> pDevice;
  2607. if (!CreateDevice(&pDevice))
  2608. return;
  2609. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Saturate", nullptr);
  2610. MappedData data;
  2611. test->Test->GetReadBackData("U0", &data);
  2612. const float *pValues = (float *)data.data();
  2613. // Everything is zero except for 1.5f and +Inf, which saturate to 1.0f
  2614. const float ExpectedCases[9] = {
  2615. 0.0f, 0.0f, 0.0f, 0.0f, // -inf, -1.5, -denorm, -0
  2616. 0.0f, 0.0f, 1.0f, 1.0f, // 0, denorm, 1.5f, inf
  2617. 0.0f // nan
  2618. };
  2619. for (size_t i = 0; i < _countof(ExpectedCases); ++i) {
  2620. VERIFY_IS_TRUE(ifdenorm_flushf_eq(*pValues, ExpectedCases[i]));
  2621. ++pValues;
  2622. }
  2623. }
  2624. void ExecutionTest::BasicTriangleTestSetup(LPCSTR ShaderOpName, LPCWSTR FileName, D3D_SHADER_MODEL testModel) {
  2625. #ifdef _HLK_CONF
  2626. UNREFERENCED_PARAMETER(ShaderOpName);
  2627. UNREFERENCED_PARAMETER(FileName);
  2628. UNREFERENCED_PARAMETER(testModel);
  2629. #else
  2630. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2631. CComPtr<IStream> pStream;
  2632. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2633. // Single operation test at the moment.
  2634. CComPtr<ID3D12Device> pDevice;
  2635. if (!CreateDevice(&pDevice, testModel))
  2636. return;
  2637. // As this is used, 6.2 requirement always comes with requiring native 16-bit ops
  2638. if (testModel == D3D_SHADER_MODEL_6_2 && !DoesDeviceSupportNative16bitOps(pDevice)) {
  2639. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  2640. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  2641. return;
  2642. }
  2643. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, ShaderOpName, nullptr);
  2644. MappedData data;
  2645. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2646. UINT width = (UINT)D.Width;
  2647. UINT height = D.Height;
  2648. test->Test->GetReadBackData("RTarget", &data);
  2649. const uint32_t *pPixels = (uint32_t *)data.data();
  2650. if (SaveImages()) {
  2651. SavePixelsToFile(pPixels, DXGI_FORMAT_R8G8B8A8_UNORM, 320, 200, FileName);
  2652. }
  2653. uint32_t top = pPixels[width / 2]; // Top center.
  2654. uint32_t mid = pPixels[width / 2 + width * (height / 2)]; // Middle center.
  2655. VERIFY_ARE_EQUAL(0xff663300, top); // clear color
  2656. VERIFY_ARE_EQUAL(0xffffffff, mid); // white
  2657. // This is the basic validation test for shader operations, so it's good to
  2658. // check this here at least for this one test case.
  2659. data.reset();
  2660. test.reset();
  2661. ReportLiveObjects();
  2662. #endif
  2663. }
  2664. TEST_F(ExecutionTest, BasicTriangleOpTest) {
  2665. BasicTriangleTestSetup("Triangle", L"basic-triangle.bmp", D3D_SHADER_MODEL_6_0);
  2666. }
  2667. TEST_F(ExecutionTest, BasicTriangleOpTestHalf) {
  2668. BasicTriangleTestSetup("TriangleHalf", L"basic-triangle-half.bmp", D3D_SHADER_MODEL_6_2);
  2669. }
  2670. void VerifyDerivResults(const float *pPixels, UINT offsetCenter) {
  2671. // pixel at the center
  2672. float CenterDDXFine = pPixels[offsetCenter];
  2673. float CenterDDYFine = pPixels[offsetCenter + 1];
  2674. float CenterDDXCoarse = pPixels[offsetCenter + 2];
  2675. float CenterDDYCoarse = pPixels[offsetCenter + 3];
  2676. LogCommentFmt(
  2677. L"center ddx_fine: %8f, ddy_fine: %8f, ddx_coarse: %8f, ddy_coarse: %8f",
  2678. CenterDDXFine, CenterDDYFine, CenterDDXCoarse, CenterDDYCoarse);
  2679. // The texture for the 9 pixels in the center should look like the following
  2680. // 256 32 64
  2681. // 2048 256 512
  2682. // 1 .125 .25
  2683. // In D3D12 there is no guarantee of how the adapter is grouping 2x2 pixels
  2684. // So for fine derivatives there can be up to two possible results for the center pixel,
  2685. // while for coarse derivatives there can be up to six possible results.
  2686. int ulpTolerance = 1;
  2687. // 512 - 256 or 2048 - 256
  2688. bool left = CompareFloatULP(CenterDDXFine, -1792.0f, ulpTolerance);
  2689. VERIFY_IS_TRUE(left || CompareFloatULP(CenterDDXFine, 256.0f, ulpTolerance));
  2690. // 256 - 32 or 256 - .125
  2691. bool top = CompareFloatULP(CenterDDYFine, 224.0f, ulpTolerance);
  2692. VERIFY_IS_TRUE(top || CompareFloatULP(CenterDDYFine, -255.875, ulpTolerance));
  2693. if (top && left) {
  2694. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -224.0f, ulpTolerance) ||
  2695. CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance)) &&
  2696. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2697. CompareFloatULP(CenterDDYCoarse, 1792.0f, ulpTolerance)));
  2698. }
  2699. else if (top) { // top right quad
  2700. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2701. CompareFloatULP(CenterDDXCoarse, 32.0f, ulpTolerance)) &&
  2702. (CompareFloatULP(CenterDDYCoarse, 224.0f, ulpTolerance) ||
  2703. CompareFloatULP(CenterDDYCoarse, 448.0f, ulpTolerance)));
  2704. }
  2705. else if (left) { // bottom left quad
  2706. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, -1792.0f, ulpTolerance) ||
  2707. CompareFloatULP(CenterDDXCoarse, -.875f, ulpTolerance)) &&
  2708. (CompareFloatULP(CenterDDYCoarse, -2047.0f, ulpTolerance) ||
  2709. CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance)));
  2710. }
  2711. else { // bottom right
  2712. VERIFY_IS_TRUE((CompareFloatULP(CenterDDXCoarse, 256.0f, ulpTolerance) ||
  2713. CompareFloatULP(CenterDDXCoarse, .125f, ulpTolerance)) &&
  2714. (CompareFloatULP(CenterDDYCoarse, -255.875f, ulpTolerance) ||
  2715. CompareFloatULP(CenterDDYCoarse, -511.75f, ulpTolerance)));
  2716. }
  2717. }
  2718. // Rendering two right triangles forming a square and assigning a texture value
  2719. // for each pixel to calculate derivates.
  2720. TEST_F(ExecutionTest, PartialDerivTest) {
  2721. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2722. CComPtr<IStream> pStream;
  2723. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2724. CComPtr<ID3D12Device> pDevice;
  2725. if (!CreateDevice(&pDevice))
  2726. return;
  2727. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "DerivFine", nullptr);
  2728. MappedData data;
  2729. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  2730. UINT width = (UINT)D.Width;
  2731. UINT height = D.Height;
  2732. UINT pixelSize = GetByteSizeForFormat(D.Format) / 4;
  2733. test->Test->GetReadBackData("RTarget", &data);
  2734. const float *pPixels = (float *)data.data();
  2735. UINT centerIndex = (UINT64)width * height / 2 - width / 2;
  2736. UINT offsetCenter = centerIndex * pixelSize;
  2737. VerifyDerivResults(pPixels, offsetCenter);
  2738. }
  2739. struct Dispatch {
  2740. int width, height, depth;
  2741. };
  2742. std::shared_ptr<st::ShaderOpTest>
  2743. RunDispatch(ID3D12Device *pDevice, dxc::DxcDllSupport &support,
  2744. st::ShaderOp *pShaderOp, const Dispatch D) {
  2745. char compilerOptions[256];
  2746. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  2747. test->SetDxcSupport(&support);
  2748. test->SetInitCallback(nullptr);
  2749. test->SetDevice(pDevice);
  2750. // format compiler args
  2751. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions),
  2752. "-D DISPATCHX=%d -D DISPATCHY=%d -D DISPATCHZ=%d ",
  2753. D.width, D.height, D.depth));
  2754. for (st::ShaderOpShader &S : pShaderOp->Shaders)
  2755. S.Arguments = compilerOptions;
  2756. pShaderOp->DispatchX = D.width;
  2757. pShaderOp->DispatchY = D.height;
  2758. pShaderOp->DispatchZ = D.depth;
  2759. test->RunShaderOp(pShaderOp);
  2760. return test;
  2761. }
  2762. TEST_F(ExecutionTest, DerivativesTest) {
  2763. const UINT pixelSize = 4; // always float4
  2764. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2765. CComPtr<IStream> pStream;
  2766. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2767. CComPtr<ID3D12Device> pDevice;
  2768. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  2769. return;
  2770. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2771. std::make_shared<st::ShaderOpSet>();
  2772. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2773. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("Derivatives");
  2774. std::vector<Dispatch> dispatches =
  2775. {
  2776. {40, 1, 1},
  2777. {1000, 1, 1},
  2778. {32, 32, 1},
  2779. {16, 64, 1},
  2780. {4, 12, 4},
  2781. {4, 64, 1},
  2782. {16, 16, 3},
  2783. {32, 8, 2}
  2784. };
  2785. std::vector<Dispatch> meshDispatches =
  2786. {
  2787. {60, 1, 1},
  2788. {128, 1, 1},
  2789. {8, 8, 1},
  2790. {32, 8, 1},
  2791. {8, 16, 4},
  2792. {8, 64, 1},
  2793. {8, 8, 3},
  2794. };
  2795. std::vector<Dispatch> badDispatches =
  2796. {
  2797. {16, 3, 1},
  2798. {2, 16, 1},
  2799. {33, 1, 1}
  2800. };
  2801. pShaderOp->UseWarpDevice = GetTestParamUseWARP(true);
  2802. LPCSTR CS = pShaderOp->CS;
  2803. MappedData data;
  2804. for (Dispatch &D : dispatches) {
  2805. // Test Compute Shader
  2806. std::shared_ptr<st::ShaderOpTest> test = RunDispatch(pDevice, m_support, pShaderOp, D);
  2807. test->GetReadBackData("U0", &data);
  2808. float *pPixels = (float *)data.data();;
  2809. UINT centerIndex = 0;
  2810. if (D.height == 1) {
  2811. centerIndex = (((UINT64)(D.width * D.height * D.depth) / 2) & ~0xF) + 10;
  2812. } else {
  2813. // To find roughly the center for compute, divide the height and width in half,
  2814. // truncate to the previous multiple of 4 to get to the start of the repeating pattern
  2815. // and then add 2 rows to get to the second row of quads and 2 to get to the first texel
  2816. // of the second row of that quad row
  2817. UINT centerRow = ((D.height/2UL) & ~0x3) + 2;
  2818. UINT centerCol = ((D.width/2UL) & ~0x3) + 2;
  2819. centerIndex = centerRow * D.width + centerCol;
  2820. }
  2821. UINT offsetCenter = centerIndex * pixelSize;
  2822. LogCommentFmt(L"Verifying derivatives in compute shader results");
  2823. VerifyDerivResults(pPixels, offsetCenter);
  2824. }
  2825. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2826. // Disable CS so mesh goes forward
  2827. pShaderOp->CS = nullptr;
  2828. for (Dispatch &D : meshDispatches) {
  2829. std::shared_ptr<st::ShaderOpTest> test = RunDispatch(pDevice, m_support, pShaderOp, D);
  2830. test->GetReadBackData("U1", &data);
  2831. const float *pPixels = (float *)data.data();
  2832. UINT centerIndex = (((UINT64)(D.width * D.height * D.depth)/2) & ~0xF) + 10;
  2833. UINT offsetCenter = centerIndex * pixelSize;
  2834. LogCommentFmt(L"Verifying derivatives in mesh shader results");
  2835. VerifyDerivResults(pPixels, offsetCenter);
  2836. test->GetReadBackData("U2", &data);
  2837. pPixels = (float *)data.data();
  2838. LogCommentFmt(L"Verifying derivatives in amplification shader results");
  2839. VerifyDerivResults(pPixels, offsetCenter);
  2840. }
  2841. }
  2842. // Final tests with invalid dispatch size just to make sure they run
  2843. for (Dispatch &D : badDispatches) {
  2844. // Test Compute Shader
  2845. pShaderOp->CS = CS;
  2846. std::shared_ptr<st::ShaderOpTest> test = RunDispatch(pDevice, m_support, pShaderOp, D);
  2847. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2848. pShaderOp->CS = nullptr;
  2849. test = RunDispatch(pDevice, m_support, pShaderOp, D);
  2850. }
  2851. }
  2852. }
  2853. // Verify the results for the quad starting with the given index
  2854. void VerifyQuadReadResults(const UINT *pPixels, UINT quadIndex) {
  2855. for (UINT i = 0; i < 4; i++) {
  2856. UINT ix = quadIndex + i;
  2857. VERIFY_ARE_EQUAL(pPixels[4*ix + 0], ix); // ReadLaneAt own quad index
  2858. VERIFY_ARE_EQUAL(pPixels[4*ix + 1], (ix^1));// ReadAcrossX
  2859. VERIFY_ARE_EQUAL(pPixels[4*ix + 2], (ix^2));// ReadAcrossY
  2860. VERIFY_ARE_EQUAL(pPixels[4*ix + 3], (ix^3));// ReadAcrossDiagonal
  2861. }
  2862. }
  2863. TEST_F(ExecutionTest, QuadReadTest) {
  2864. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2865. CComPtr<IStream> pStream;
  2866. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2867. CComPtr<ID3D12Device> pDevice;
  2868. if (!CreateDevice(&pDevice))
  2869. return;
  2870. if (GetTestParamUseWARP(UseWarpByDefault()) || IsDeviceBasicAdapter(pDevice)) {
  2871. WEX::Logging::Log::Comment(L"WARP does not support QuadRead in compute shaders.");
  2872. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  2873. return;
  2874. }
  2875. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2876. std::make_shared<st::ShaderOpSet>();
  2877. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2878. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("QuadRead");
  2879. LPCSTR CS = pShaderOp->CS;
  2880. struct Dispatch {
  2881. int x, y, z;
  2882. int mx, my, mz;
  2883. };
  2884. //std::vector<std::tuple<int, int, int, int, int>> dispatches =
  2885. std::vector<Dispatch> dispatches =
  2886. {
  2887. {32, 32, 1, 8, 8, 1},
  2888. {64, 4, 1, 64, 2, 1},
  2889. {1, 4, 64, 1, 4, 32},
  2890. {64, 1, 1, 64, 1, 1},
  2891. {1, 64, 1, 1, 64, 1},
  2892. {1, 1, 64, 1, 1, 64},
  2893. {16, 16, 3, 4, 4, 3},
  2894. {32, 3, 8, 8, 3, 2},
  2895. {3, 1, 64, 3, 1, 32}
  2896. };
  2897. for (Dispatch &D : dispatches) {
  2898. UINT width = D.x;
  2899. UINT height = D.y;
  2900. UINT depth = D.z;
  2901. UINT mwidth = D.mx;
  2902. UINT mheight = D.my;
  2903. UINT mdepth = D.mz;
  2904. // format compiler args
  2905. char compilerOptions[256];
  2906. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions),
  2907. "-D DISPATCHX=%d -D DISPATCHY=%d -D DISPATCHZ=%d "
  2908. "-D MESHDISPATCHX=%d -D MESHDISPATCHY=%d -D MESHDISPATCHZ=%d",
  2909. width, height, depth, mwidth, mheight, mdepth));
  2910. for (st::ShaderOpShader &S : pShaderOp->Shaders)
  2911. S.Arguments = compilerOptions;
  2912. pShaderOp->DispatchX = width;
  2913. pShaderOp->DispatchY = height;
  2914. pShaderOp->DispatchZ = depth;
  2915. // Test Compute Shader
  2916. pShaderOp->CS = CS;
  2917. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "QuadRead", nullptr, ShaderOpSet);
  2918. MappedData data;
  2919. test->Test->GetReadBackData("U0", &data);
  2920. const UINT *pPixels = (UINT *)data.data();
  2921. // To find roughly the center for compute, divide the pixel count in half
  2922. // and truncate to next lowest power of 4 to start at a quad
  2923. UINT offsetCenter = ((UINT64)(width * height * depth)/2) & ~0x3;
  2924. // Test first, second and center quads
  2925. LogCommentFmt(L"Verifying QuadRead* in compute shader results");
  2926. VerifyQuadReadResults(pPixels, 0);
  2927. VerifyQuadReadResults(pPixels, 4);
  2928. VerifyQuadReadResults(pPixels, offsetCenter);
  2929. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  2930. offsetCenter = ((UINT64)(mwidth * mheight * mdepth)/2) & ~0x3;
  2931. // Disable CS so mesh goes forward
  2932. pShaderOp->CS = nullptr;
  2933. test = RunShaderOpTestAfterParse(pDevice, m_support, "QuadRead", nullptr, ShaderOpSet);
  2934. test->Test->GetReadBackData("U1", &data);
  2935. pPixels = (UINT *)data.data();
  2936. // Test first, second and center quads
  2937. LogCommentFmt(L"Verifying QuadRead* in mesh shader results");
  2938. VerifyQuadReadResults(pPixels, 0);
  2939. VerifyQuadReadResults(pPixels, 4);
  2940. VerifyQuadReadResults(pPixels, offsetCenter);
  2941. test->Test->GetReadBackData("U2", &data);
  2942. pPixels = (UINT *)data.data();
  2943. // Test first, second and center quads
  2944. LogCommentFmt(L"Verifying QuadRead* in amplification shader results");
  2945. VerifyQuadReadResults(pPixels, 0);
  2946. VerifyQuadReadResults(pPixels, 4);
  2947. VerifyQuadReadResults(pPixels, offsetCenter);
  2948. }
  2949. }
  2950. }
  2951. void VerifySampleResults(const UINT *pPixels, UINT width) {
  2952. UINT xlod = 0;
  2953. UINT ylod = 0;
  2954. // Each pixel contains 4 samples and 4 LOD calculations.
  2955. // 2 of these (called 'left' and 'right') have X values that vary and a constant Y
  2956. // 2 others (called 'top' and 'bot') have Y values that vary and a constant X
  2957. // Only of the X variant sample results and one of the Y variant results
  2958. // are actually reported for the pixel.
  2959. // The other 2 serve as "helpers" to the other pixels in the quad.
  2960. // On the left side of the quad, the 'left' samples are reported.
  2961. // Op the top of the quad, the 'top' samples are reported and so on.
  2962. // The varying coordinate values alternate between zero and a
  2963. // value whose magnitude increases with the index.
  2964. // As a result, the LOD level should steadily increas.
  2965. // Due to vagaries of implementation, the same derivatives
  2966. // in both directions might result in different levels for different locations
  2967. // in the quad. So only comparisons between sample results and LOD calculations
  2968. // and ensuring that the LOD increased and reaches the max can be tested reliably.
  2969. for (unsigned i = 0; i < width; i++) {
  2970. // CalculateLOD and Sample from texture with mip levels containing LOD index should match
  2971. VERIFY_ARE_EQUAL(pPixels[4*i + 0], pPixels[4*i + 1]);
  2972. VERIFY_ARE_EQUAL(pPixels[4*i + 2], pPixels[4*i + 3]);
  2973. // Make sure LODs are ever climbing as magnitudes increase
  2974. VERIFY_IS_TRUE(pPixels[4*i] >= xlod);
  2975. xlod = pPixels[4*i];
  2976. VERIFY_IS_TRUE(pPixels[4*i + 2] >= ylod);
  2977. ylod = pPixels[4*i + 2];
  2978. }
  2979. // Make sure we reached the max lod level for both tracks
  2980. VERIFY_ARE_EQUAL(xlod, 6u);
  2981. VERIFY_ARE_EQUAL(ylod, 6u);
  2982. }
  2983. TEST_F(ExecutionTest, ComputeSampleTest) {
  2984. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  2985. CComPtr<IStream> pStream;
  2986. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  2987. CComPtr<ID3D12Device> pDevice;
  2988. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  2989. return;
  2990. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  2991. std::make_shared<st::ShaderOpSet>();
  2992. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  2993. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("ComputeSample");
  2994. // Initialize texture with the LOD number in each corresponding mip level
  2995. auto SampleInitFn = [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  2996. UNREFERENCED_PARAMETER(pShaderOp);
  2997. VERIFY_ARE_EQUAL(0, _stricmp(Name, "T0"));
  2998. D3D12_RESOURCE_DESC &texDesc = pShaderOp->GetResourceByName("T0")->Desc;
  2999. UINT texWidth = (UINT)texDesc.Width;
  3000. UINT texHeight = (UINT)texDesc.Height;
  3001. size_t size = sizeof(float) * texWidth * texHeight * 2;
  3002. Data.resize(size);
  3003. float *pPrimitives = (float *)Data.data();
  3004. float lod = 0.0;
  3005. int ix = 0;
  3006. while (texHeight > 0 && texWidth > 0) {
  3007. if(!texHeight) texHeight = 1;
  3008. if(!texWidth) texWidth = 1;
  3009. for (size_t j = 0; j < texHeight; ++j) {
  3010. for (size_t i = 0; i < texWidth; ++i) {
  3011. pPrimitives[ix++] = lod;
  3012. }
  3013. }
  3014. lod += 1.0;
  3015. texHeight >>= 1;
  3016. texWidth >>= 1;
  3017. }
  3018. };
  3019. LPCSTR CS2 = nullptr, AS2 = nullptr, MS2 = nullptr;
  3020. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  3021. if (!strcmp(S.Name, "CS2")) CS2 = S.Name;
  3022. if (!strcmp(S.Name, "AS2")) AS2 = S.Name;
  3023. if (!strcmp(S.Name, "MS2")) MS2 = S.Name;
  3024. }
  3025. // Test 1D compute shader
  3026. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  3027. MappedData data;
  3028. test->Test->GetReadBackData("U0", &data);
  3029. const UINT *pPixels = (UINT *)data.data();
  3030. VerifySampleResults(pPixels, 84*4);
  3031. // Test 2D compute shader
  3032. pShaderOp->CS = CS2;
  3033. test.reset();
  3034. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  3035. test->Test->GetReadBackData("U0", &data);
  3036. pPixels = (UINT *)data.data();
  3037. VerifySampleResults(pPixels, 84*4);
  3038. if (DoesDeviceSupportMeshAmpDerivatives(pDevice)) {
  3039. // Disable CS so mesh goes forward
  3040. pShaderOp->CS = nullptr;
  3041. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  3042. test->Test->GetReadBackData("U1", &data);
  3043. pPixels = (UINT *)data.data();
  3044. VerifySampleResults(pPixels, 116);
  3045. test->Test->GetReadBackData("U2", &data);
  3046. pPixels = (UINT *)data.data();
  3047. VerifySampleResults(pPixels, 84);
  3048. pShaderOp->AS = AS2;
  3049. pShaderOp->MS = MS2;
  3050. test = RunShaderOpTestAfterParse(pDevice, m_support, "ComputeSample", SampleInitFn, ShaderOpSet);
  3051. test->Test->GetReadBackData("U1", &data);
  3052. pPixels = (UINT *)data.data();
  3053. VerifySampleResults(pPixels, 116);
  3054. test->Test->GetReadBackData("U2", &data);
  3055. pPixels = (UINT *)data.data();
  3056. VerifySampleResults(pPixels, 84);
  3057. }
  3058. }
  3059. // Executing a simple binop to verify shadel model 6.1 support; runs with
  3060. // ShaderModel61.CoreRequirement
  3061. TEST_F(ExecutionTest, BasicShaderModel61) {
  3062. RunBasicShaderModelTest(D3D_SHADER_MODEL_6_1);
  3063. }
  3064. // Executing a simple binop to verify shadel model 6.3 support; runs with
  3065. // ShaderModel63.CoreRequirement
  3066. TEST_F(ExecutionTest, BasicShaderModel63) {
  3067. RunBasicShaderModelTest(D3D_SHADER_MODEL_6_3);
  3068. }
  3069. void ExecutionTest::RunBasicShaderModelTest(D3D_SHADER_MODEL shaderModel) {
  3070. WEX::TestExecution::SetVerifyOutput verifySettings(
  3071. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  3072. CComPtr<ID3D12Device> pDevice;
  3073. if (!CreateDevice(&pDevice, shaderModel)) {
  3074. return;
  3075. }
  3076. char *pShaderModelStr;
  3077. if (shaderModel == D3D_SHADER_MODEL_6_1) {
  3078. pShaderModelStr = "cs_6_1";
  3079. } else if (shaderModel == D3D_SHADER_MODEL_6_3) {
  3080. pShaderModelStr = "cs_6_3";
  3081. } else {
  3082. DXASSERT_NOMSG("Invalid Shader Model Parameter");
  3083. pShaderModelStr = nullptr;
  3084. }
  3085. const char shaderTemplate[] =
  3086. "struct SBinaryOp { %s input1; %s input2; %s output; };"
  3087. "RWStructuredBuffer<SBinaryOp> g_buf : register(u0);"
  3088. "[numthreads(8,8,1)]"
  3089. "void main(uint GI : SV_GroupIndex) {"
  3090. " SBinaryOp l = g_buf[GI];"
  3091. " l.output = l.input1 + l.input2;"
  3092. " g_buf[GI] = l;"
  3093. "}";
  3094. char shader[sizeof(shaderTemplate) + 50];
  3095. // Run simple shader with float data types
  3096. char* sTy = "float";
  3097. float inputFloatPairs[] = { 1.5f, -2.8f, 3.23e-5f, 6.0f, 181.621f, 14.978f };
  3098. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3099. WEX::Logging::Log::Comment(L"BasicShaderModel float");
  3100. RunBasicShaderModelTest<float>(pDevice, pShaderModelStr, shader, inputFloatPairs, sizeof(inputFloatPairs) / (2 * sizeof(float)));
  3101. // Run simple shader with double data types
  3102. if (DoesDeviceSupportDouble(pDevice)) {
  3103. sTy = "double";
  3104. double inputDoublePairs[] = { 1.5891020, -2.8, 3.23e-5, 1 / 3, 181.91621, 14.654978 };
  3105. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3106. WEX::Logging::Log::Comment(L"BasicShaderModel double");
  3107. RunBasicShaderModelTest<double>(pDevice, pShaderModelStr, shader, inputDoublePairs, sizeof(inputDoublePairs) / (2 * sizeof(double)));
  3108. }
  3109. else {
  3110. // Optional feature, so it's correct to not support it if declared as such.
  3111. WEX::Logging::Log::Comment(L"Device does not support double operations.");
  3112. }
  3113. // Run simple shader with int64 types
  3114. if (DoesDeviceSupportInt64(pDevice)) {
  3115. sTy = "int64_t";
  3116. int64_t inputInt64Pairs[] = { 1, -100, 6814684, -9814810, 654, 1021248900 };
  3117. VERIFY_IS_TRUE(sprintf(shader, shaderTemplate, sTy, sTy, sTy) > 0);
  3118. WEX::Logging::Log::Comment(L"BasicShaderModel int64_t");
  3119. RunBasicShaderModelTest<int64_t>(pDevice, pShaderModelStr, shader, inputInt64Pairs, sizeof(inputInt64Pairs) / (2 * sizeof(int64_t)));
  3120. }
  3121. else {
  3122. // Optional feature, so it's correct to not support it if declared as such.
  3123. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  3124. }
  3125. }
  3126. template <class Ty>
  3127. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString() {
  3128. DXASSERT_NOMSG("Unsupported type");
  3129. return "";
  3130. }
  3131. template <>
  3132. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<float>() {
  3133. return L"element #%u: input1 = %6.8f, input1 = %6.8f, output = %6.8f, expected = %6.8f";
  3134. }
  3135. template <>
  3136. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<double>() {
  3137. return BasicShaderModelTest_GetFormatString<float>();
  3138. }
  3139. template <>
  3140. const wchar_t* ExecutionTest::BasicShaderModelTest_GetFormatString<int64_t>() {
  3141. return L"element #%u: input1 = %ld, input1 = %ld, output = %ld, expected = %ld";
  3142. }
  3143. template <class Ty>
  3144. void ExecutionTest::RunBasicShaderModelTest(CComPtr<ID3D12Device> pDevice, const char *pShaderModelStr, const char *pShader,
  3145. Ty *pInputDataPairs, unsigned inputDataCount) {
  3146. struct SBinaryOp {
  3147. Ty input1;
  3148. Ty input2;
  3149. Ty output;
  3150. };
  3151. CComPtr<IStream> pStream;
  3152. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  3153. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  3154. pDevice, m_support, pStream, "BinaryFPOp",
  3155. // this callbacked is called when the test is creating the resource to run the test
  3156. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  3157. UNREFERENCED_PARAMETER(Name);
  3158. pShaderOp->Shaders.at(0).Target = pShaderModelStr;
  3159. pShaderOp->Shaders.at(0).Text = pShader;
  3160. size_t size = sizeof(SBinaryOp) * inputDataCount;
  3161. Data.resize(size);
  3162. SBinaryOp *pPrimitives = (SBinaryOp*)Data.data();
  3163. Ty *pIn = pInputDataPairs;
  3164. for (size_t i = 0; i < inputDataCount; i++, pIn += 2) {
  3165. SBinaryOp *p = &pPrimitives[i];
  3166. p->input1 = pIn[0];
  3167. p->input2 = pIn[1];
  3168. }
  3169. });
  3170. VERIFY_SUCCEEDED(S_OK);
  3171. MappedData data;
  3172. test->Test->GetReadBackData("SBinaryFPOp", &data);
  3173. SBinaryOp *pPrimitives = (SBinaryOp*)data.data();
  3174. const wchar_t* formatStr = BasicShaderModelTest_GetFormatString<Ty>();
  3175. Ty *pIn = pInputDataPairs;
  3176. for (unsigned i = 0; i < inputDataCount; i++, pIn += 2) {
  3177. Ty expValue = pIn[0] + pIn[1];
  3178. SBinaryOp *p = &pPrimitives[i];
  3179. LogCommentFmt(formatStr, i, pIn[0], pIn[1], p->output, expValue);
  3180. VERIFY_ARE_EQUAL(p->output, expValue);
  3181. }
  3182. }
  3183. // Resource structure for data-driven tests.
  3184. struct SUnaryFPOp {
  3185. float input;
  3186. float output;
  3187. };
  3188. struct SBinaryFPOp {
  3189. float input1;
  3190. float input2;
  3191. float output1;
  3192. float output2;
  3193. };
  3194. struct STertiaryFPOp {
  3195. float input1;
  3196. float input2;
  3197. float input3;
  3198. float output;
  3199. };
  3200. struct SUnaryHalfOp {
  3201. uint16_t input;
  3202. uint16_t output;
  3203. };
  3204. struct SBinaryHalfOp {
  3205. uint16_t input1;
  3206. uint16_t input2;
  3207. uint16_t output1;
  3208. uint16_t output2;
  3209. };
  3210. struct STertiaryHalfOp {
  3211. uint16_t input1;
  3212. uint16_t input2;
  3213. uint16_t input3;
  3214. uint16_t output;
  3215. };
  3216. struct SUnaryIntOp {
  3217. int input;
  3218. int output;
  3219. };
  3220. struct SUnaryUintOp {
  3221. unsigned int input;
  3222. unsigned int output;
  3223. };
  3224. struct SBinaryIntOp {
  3225. int input1;
  3226. int input2;
  3227. int output1;
  3228. int output2;
  3229. };
  3230. struct STertiaryIntOp {
  3231. int input1;
  3232. int input2;
  3233. int input3;
  3234. int output;
  3235. };
  3236. struct SBinaryUintOp {
  3237. unsigned int input1;
  3238. unsigned int input2;
  3239. unsigned int output1;
  3240. unsigned int output2;
  3241. };
  3242. struct STertiaryUintOp {
  3243. unsigned int input1;
  3244. unsigned int input2;
  3245. unsigned int input3;
  3246. unsigned int output;
  3247. };
  3248. struct SUnaryInt16Op {
  3249. short input;
  3250. short output;
  3251. };
  3252. struct SUnaryUint16Op {
  3253. unsigned short input;
  3254. unsigned short output;
  3255. };
  3256. struct SBinaryInt16Op {
  3257. short input1;
  3258. short input2;
  3259. short output1;
  3260. short output2;
  3261. };
  3262. struct STertiaryInt16Op {
  3263. short input1;
  3264. short input2;
  3265. short input3;
  3266. short output;
  3267. };
  3268. struct SBinaryUint16Op {
  3269. unsigned short input1;
  3270. unsigned short input2;
  3271. unsigned short output1;
  3272. unsigned short output2;
  3273. };
  3274. struct STertiaryUint16Op {
  3275. unsigned short input1;
  3276. unsigned short input2;
  3277. unsigned short input3;
  3278. unsigned short output;
  3279. };
  3280. // representation for HLSL float vectors
  3281. struct SDotOp {
  3282. XMFLOAT4 input1;
  3283. XMFLOAT4 input2;
  3284. float o_dot2;
  3285. float o_dot3;
  3286. float o_dot4;
  3287. };
  3288. struct Half2
  3289. {
  3290. uint16_t x;
  3291. uint16_t y;
  3292. Half2() = default;
  3293. Half2(const Half2&) = default;
  3294. Half2& operator=(const Half2&) = default;
  3295. Half2(Half2&&) = default;
  3296. Half2& operator=(Half2&&) = default;
  3297. constexpr Half2(uint16_t _x, uint16_t _y) : x(_x), y(_y) {}
  3298. explicit Half2(_In_reads_(2) const uint16_t *pArray) : x(pArray[0]), y(pArray[1]) {}
  3299. };
  3300. struct SDot2AddHalfOp {
  3301. Half2 input1;
  3302. Half2 input2;
  3303. float acc;
  3304. float result;
  3305. };
  3306. struct SDot4AddI8PackedOp {
  3307. uint32_t input1;
  3308. uint32_t input2;
  3309. int32_t acc;
  3310. int32_t result;
  3311. };
  3312. struct SDot4AddU8PackedOp {
  3313. uint32_t input1;
  3314. uint32_t input2;
  3315. uint32_t acc;
  3316. uint32_t result;
  3317. };
  3318. struct SMsad4 {
  3319. unsigned int ref;
  3320. XMUINT2 src;
  3321. XMUINT4 accum;
  3322. XMUINT4 result;
  3323. };
  3324. struct SPackUnpackOpOutPacked
  3325. {
  3326. uint32_t packedUint32;
  3327. uint32_t packedInt32;
  3328. uint32_t packedUint16;
  3329. uint32_t packedInt16;
  3330. uint32_t packedClampedUint32;
  3331. uint32_t packedClampedInt32;
  3332. uint32_t packedClampedUint16;
  3333. uint32_t packedClampedInt16;
  3334. };
  3335. struct SPackUnpackOpOutUnpacked {
  3336. std::array<uint32_t, 4> outputUint32;
  3337. std::array<int32_t, 4> outputInt32;
  3338. std::array<uint16_t, 4> outputUint16;
  3339. std::array<int16_t, 4> outputInt16;
  3340. std::array<uint32_t, 4> outputClampedUint32;
  3341. std::array<int32_t, 4> outputClampedInt32;
  3342. std::array<uint16_t, 4> outputClampedUint16;
  3343. std::array<int16_t, 4> outputClampedInt16;
  3344. };
  3345. // Parameter representation for taef data-driven tests
  3346. struct TableParameter {
  3347. LPCWSTR m_name;
  3348. enum TableParameterType {
  3349. INT8,
  3350. INT16,
  3351. INT32,
  3352. UINT,
  3353. FLOAT,
  3354. HALF,
  3355. DOUBLE,
  3356. STRING,
  3357. BOOL,
  3358. INT8_TABLE,
  3359. INT16_TABLE,
  3360. INT32_TABLE,
  3361. FLOAT_TABLE,
  3362. HALF_TABLE,
  3363. DOUBLE_TABLE,
  3364. STRING_TABLE,
  3365. UINT8_TABLE,
  3366. UINT16_TABLE,
  3367. UINT32_TABLE,
  3368. BOOL_TABLE
  3369. };
  3370. TableParameterType m_type;
  3371. bool m_required; // required parameter
  3372. int8_t m_int8;
  3373. int16_t m_int16;
  3374. int m_int32;
  3375. unsigned int m_uint;
  3376. float m_float;
  3377. uint16_t m_half; // no such thing as half type in c++. Use int16 instead
  3378. double m_double;
  3379. bool m_bool;
  3380. WEX::Common::String m_str;
  3381. std::vector<int8_t> m_int8Table;
  3382. std::vector<int16_t> m_int16Table;
  3383. std::vector<int> m_int32Table;
  3384. std::vector<uint8_t> m_uint8Table;
  3385. std::vector<uint16_t> m_uint16Table;
  3386. std::vector<unsigned int> m_uint32Table;
  3387. std::vector<float> m_floatTable;
  3388. std::vector<uint16_t> m_halfTable; // no such thing as half type in c++
  3389. std::vector<double> m_doubleTable;
  3390. std::vector<bool> m_boolTable;
  3391. std::vector<WEX::Common::String> m_StringTable;
  3392. };
  3393. class TableParameterHandler {
  3394. private:
  3395. HRESULT ParseTableRow();
  3396. public:
  3397. TableParameter* m_table;
  3398. size_t m_tableSize;
  3399. TableParameterHandler(TableParameter *pTable, size_t size) : m_table(pTable), m_tableSize(size) {
  3400. clearTableParameter();
  3401. VERIFY_SUCCEEDED(ParseTableRow());
  3402. }
  3403. TableParameter* GetTableParamByName(LPCWSTR name) {
  3404. for (size_t i = 0; i < m_tableSize; ++i) {
  3405. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3406. return &m_table[i];
  3407. }
  3408. }
  3409. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3410. return nullptr;
  3411. }
  3412. void clearTableParameter() {
  3413. for (size_t i = 0; i < m_tableSize; ++i) {
  3414. m_table[i].m_int32 = 0;
  3415. m_table[i].m_uint = 0;
  3416. m_table[i].m_double = 0;
  3417. m_table[i].m_bool = false;
  3418. m_table[i].m_str = WEX::Common::String();
  3419. }
  3420. }
  3421. template <class T1>
  3422. std::vector<T1> *GetDataArray(LPCWSTR name) {
  3423. return nullptr;
  3424. }
  3425. template <>
  3426. std::vector<int> *GetDataArray(LPCWSTR name) {
  3427. for (size_t i = 0; i < m_tableSize; ++i) {
  3428. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3429. return &(m_table[i].m_int32Table);
  3430. }
  3431. }
  3432. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3433. return nullptr;
  3434. }
  3435. template <>
  3436. std::vector<int8_t> *GetDataArray(LPCWSTR name) {
  3437. for (size_t i = 0; i < m_tableSize; ++i) {
  3438. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3439. return &(m_table[i].m_int8Table);
  3440. }
  3441. }
  3442. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3443. return nullptr;
  3444. }
  3445. template <>
  3446. std::vector<int16_t> *GetDataArray(LPCWSTR name) {
  3447. for (size_t i = 0; i < m_tableSize; ++i) {
  3448. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3449. return &(m_table[i].m_int16Table);
  3450. }
  3451. }
  3452. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3453. return nullptr;
  3454. }
  3455. template <>
  3456. std::vector<unsigned int> *GetDataArray(LPCWSTR name) {
  3457. for (size_t i = 0; i < m_tableSize; ++i) {
  3458. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3459. return &(m_table[i].m_uint32Table);
  3460. }
  3461. }
  3462. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3463. return nullptr;
  3464. }
  3465. template <>
  3466. std::vector<float> *GetDataArray(LPCWSTR name) {
  3467. for (size_t i = 0; i < m_tableSize; ++i) {
  3468. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3469. return &(m_table[i].m_floatTable);
  3470. }
  3471. }
  3472. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3473. return nullptr;
  3474. }
  3475. // TODO: uin16_t may be used to represent two different types when we introduce uint16
  3476. template <>
  3477. std::vector<uint16_t> *GetDataArray(LPCWSTR name) {
  3478. for (size_t i = 0; i < m_tableSize; ++i) {
  3479. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3480. return &(m_table[i].m_halfTable);
  3481. }
  3482. }
  3483. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3484. return nullptr;
  3485. }
  3486. template <>
  3487. std::vector<double> *GetDataArray(LPCWSTR name) {
  3488. for (size_t i = 0; i < m_tableSize; ++i) {
  3489. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3490. return &(m_table[i].m_doubleTable);
  3491. }
  3492. }
  3493. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3494. return nullptr;
  3495. }
  3496. template <>
  3497. std::vector<bool> *GetDataArray(LPCWSTR name) {
  3498. for (size_t i = 0; i < m_tableSize; ++i) {
  3499. if (_wcsicmp(name, m_table[i].m_name) == 0) {
  3500. return &(m_table[i].m_boolTable);
  3501. }
  3502. }
  3503. DXASSERT_ARGS(false, "Invalid Table Parameter Name %s", name);
  3504. return nullptr;
  3505. }
  3506. };
  3507. static TableParameter UnaryFPOpParameters[] = {
  3508. { L"ShaderOp.Target", TableParameter::STRING, true },
  3509. { L"ShaderOp.Text", TableParameter::STRING, true },
  3510. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3511. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3512. { L"Validation.Type", TableParameter::STRING, true },
  3513. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3514. { L"Warp.Version", TableParameter::UINT, false }
  3515. };
  3516. static TableParameter BinaryFPOpParameters[] = {
  3517. { L"ShaderOp.Target", TableParameter::STRING, true },
  3518. { L"ShaderOp.Text", TableParameter::STRING, true },
  3519. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3520. { L"Validation.Input2", TableParameter::FLOAT_TABLE, true },
  3521. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3522. { L"Validation.Expected2", TableParameter::FLOAT_TABLE, false },
  3523. { L"Validation.Type", TableParameter::STRING, true },
  3524. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3525. };
  3526. static TableParameter TertiaryFPOpParameters[] = {
  3527. { L"ShaderOp.Target", TableParameter::STRING, true },
  3528. { L"ShaderOp.Text", TableParameter::STRING, true },
  3529. { L"Validation.Input1", TableParameter::FLOAT_TABLE, true },
  3530. { L"Validation.Input2", TableParameter::FLOAT_TABLE, true },
  3531. { L"Validation.Input3", TableParameter::FLOAT_TABLE, true },
  3532. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3533. { L"Validation.Type", TableParameter::STRING, true },
  3534. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3535. };
  3536. static TableParameter UnaryHalfOpParameters[] = {
  3537. { L"ShaderOp.Target", TableParameter::STRING, true },
  3538. { L"ShaderOp.Text", TableParameter::STRING, true },
  3539. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3540. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3541. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3542. { L"Validation.Type", TableParameter::STRING, true },
  3543. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3544. { L"Warp.Version", TableParameter::UINT, false }
  3545. };
  3546. static TableParameter BinaryHalfOpParameters[] = {
  3547. { L"ShaderOp.Target", TableParameter::STRING, true },
  3548. { L"ShaderOp.Text", TableParameter::STRING, true },
  3549. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3550. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3551. { L"Validation.Input2", TableParameter::HALF_TABLE, true },
  3552. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3553. { L"Validation.Expected2", TableParameter::HALF_TABLE, false },
  3554. { L"Validation.Type", TableParameter::STRING, true },
  3555. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3556. };
  3557. static TableParameter TertiaryHalfOpParameters[] = {
  3558. { L"ShaderOp.Target", TableParameter::STRING, true },
  3559. { L"ShaderOp.Text", TableParameter::STRING, true },
  3560. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3561. { L"Validation.Input1", TableParameter::HALF_TABLE, true },
  3562. { L"Validation.Input2", TableParameter::HALF_TABLE, true },
  3563. { L"Validation.Input3", TableParameter::HALF_TABLE, true },
  3564. { L"Validation.Expected1", TableParameter::HALF_TABLE, true },
  3565. { L"Validation.Type", TableParameter::STRING, true },
  3566. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3567. };
  3568. static TableParameter UnaryIntOpParameters[] = {
  3569. { L"ShaderOp.Target", TableParameter::STRING, true },
  3570. { L"ShaderOp.Text", TableParameter::STRING, true },
  3571. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3572. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3573. { L"Validation.Tolerance", TableParameter::INT32, true },
  3574. };
  3575. static TableParameter UnaryUintOpParameters[] = {
  3576. { L"ShaderOp.Target", TableParameter::STRING, true },
  3577. { L"ShaderOp.Text", TableParameter::STRING, true },
  3578. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3579. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3580. { L"Validation.Tolerance", TableParameter::INT32, true },
  3581. };
  3582. static TableParameter BinaryIntOpParameters[] = {
  3583. { L"ShaderOp.Target", TableParameter::STRING, true },
  3584. { L"ShaderOp.Text", TableParameter::STRING, true },
  3585. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3586. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  3587. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3588. { L"Validation.Expected2", TableParameter::INT32_TABLE, false },
  3589. { L"Validation.Tolerance", TableParameter::INT32, true },
  3590. };
  3591. static TableParameter TertiaryIntOpParameters[] = {
  3592. { L"ShaderOp.Target", TableParameter::STRING, true },
  3593. { L"ShaderOp.Text", TableParameter::STRING, true },
  3594. { L"Validation.Input1", TableParameter::INT32_TABLE, true },
  3595. { L"Validation.Input2", TableParameter::INT32_TABLE, true },
  3596. { L"Validation.Input3", TableParameter::INT32_TABLE, true },
  3597. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3598. { L"Validation.Tolerance", TableParameter::INT32, true },
  3599. };
  3600. static TableParameter BinaryUintOpParameters[] = {
  3601. { L"ShaderOp.Target", TableParameter::STRING, true },
  3602. { L"ShaderOp.Text", TableParameter::STRING, true },
  3603. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3604. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3605. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3606. { L"Validation.Expected2", TableParameter::UINT32_TABLE, false },
  3607. { L"Validation.Tolerance", TableParameter::INT32, true },
  3608. };
  3609. static TableParameter TertiaryUintOpParameters[] = {
  3610. { L"ShaderOp.Target", TableParameter::STRING, true },
  3611. { L"ShaderOp.Text", TableParameter::STRING, true },
  3612. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3613. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3614. { L"Validation.Input3", TableParameter::UINT32_TABLE, true },
  3615. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3616. { L"Validation.Tolerance", TableParameter::INT32, true },
  3617. };
  3618. static TableParameter UnaryInt16OpParameters[] = {
  3619. { L"ShaderOp.Target", TableParameter::STRING, true },
  3620. { L"ShaderOp.Text", TableParameter::STRING, true },
  3621. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3622. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3623. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3624. { L"Validation.Tolerance", TableParameter::INT32, true },
  3625. };
  3626. static TableParameter UnaryUint16OpParameters[] = {
  3627. { L"ShaderOp.Target", TableParameter::STRING, true },
  3628. { L"ShaderOp.Text", TableParameter::STRING, true },
  3629. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3630. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3631. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3632. { L"Validation.Tolerance", TableParameter::INT32, true },
  3633. };
  3634. static TableParameter BinaryInt16OpParameters[] = {
  3635. { L"ShaderOp.Target", TableParameter::STRING, true },
  3636. { L"ShaderOp.Text", TableParameter::STRING, true },
  3637. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3638. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3639. { L"Validation.Input2", TableParameter::INT16_TABLE, true },
  3640. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3641. { L"Validation.Expected2", TableParameter::INT16_TABLE, false },
  3642. { L"Validation.Tolerance", TableParameter::INT32, true },
  3643. };
  3644. static TableParameter TertiaryInt16OpParameters[] = {
  3645. { L"ShaderOp.Target", TableParameter::STRING, true },
  3646. { L"ShaderOp.Text", TableParameter::STRING, true },
  3647. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3648. { L"Validation.Input1", TableParameter::INT16_TABLE, true },
  3649. { L"Validation.Input2", TableParameter::INT16_TABLE, true },
  3650. { L"Validation.Input3", TableParameter::INT16_TABLE, true },
  3651. { L"Validation.Expected1", TableParameter::INT16_TABLE, true },
  3652. { L"Validation.Tolerance", TableParameter::INT32, true },
  3653. };
  3654. static TableParameter BinaryUint16OpParameters[] = {
  3655. { L"ShaderOp.Target", TableParameter::STRING, true },
  3656. { L"ShaderOp.Text", TableParameter::STRING, true },
  3657. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3658. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3659. { L"Validation.Input2", TableParameter::UINT16_TABLE, true },
  3660. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3661. { L"Validation.Expected2", TableParameter::UINT16_TABLE, false },
  3662. { L"Validation.Tolerance", TableParameter::INT32, true },
  3663. };
  3664. static TableParameter TertiaryUint16OpParameters[] = {
  3665. { L"ShaderOp.Target", TableParameter::STRING, true },
  3666. { L"ShaderOp.Text", TableParameter::STRING, true },
  3667. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3668. { L"Validation.Input1", TableParameter::UINT16_TABLE, true },
  3669. { L"Validation.Input2", TableParameter::UINT16_TABLE, true },
  3670. { L"Validation.Input3", TableParameter::UINT16_TABLE, true },
  3671. { L"Validation.Expected1", TableParameter::UINT16_TABLE, true },
  3672. { L"Validation.Tolerance", TableParameter::INT32, true },
  3673. };
  3674. static TableParameter DotOpParameters[] = {
  3675. { L"ShaderOp.Target", TableParameter::STRING, true },
  3676. { L"ShaderOp.Text", TableParameter::STRING, true },
  3677. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3678. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3679. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3680. { L"Validation.Expected2", TableParameter::STRING_TABLE, true },
  3681. { L"Validation.Expected3", TableParameter::STRING_TABLE, true },
  3682. { L"Validation.Type", TableParameter::STRING, true },
  3683. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3684. };
  3685. static TableParameter Dot2AddHalfOpParameters[] = {
  3686. { L"ShaderOp.Target", TableParameter::STRING, true },
  3687. { L"ShaderOp.Text", TableParameter::STRING, true },
  3688. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3689. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3690. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3691. { L"Validation.Input3", TableParameter::FLOAT_TABLE, true },
  3692. { L"Validation.Expected1", TableParameter::FLOAT_TABLE, true },
  3693. { L"Validation.Type", TableParameter::STRING, true },
  3694. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3695. };
  3696. static TableParameter Dot4AddI8PackedOpParameters[] = {
  3697. { L"ShaderOp.Target", TableParameter::STRING, true },
  3698. { L"ShaderOp.Text", TableParameter::STRING, true },
  3699. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3700. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3701. { L"Validation.Input3", TableParameter::INT32_TABLE, true },
  3702. { L"Validation.Expected1", TableParameter::INT32_TABLE, true },
  3703. };
  3704. static TableParameter Dot4AddU8PackedOpParameters[] = {
  3705. { L"ShaderOp.Target", TableParameter::STRING, true },
  3706. { L"ShaderOp.Text", TableParameter::STRING, true },
  3707. { L"Validation.Input1", TableParameter::UINT32_TABLE, true },
  3708. { L"Validation.Input2", TableParameter::UINT32_TABLE, true },
  3709. { L"Validation.Input3", TableParameter::UINT32_TABLE, true },
  3710. { L"Validation.Expected1", TableParameter::UINT32_TABLE, true },
  3711. };
  3712. static TableParameter Msad4OpParameters[] = {
  3713. { L"ShaderOp.Text", TableParameter::STRING, true },
  3714. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3715. { L"Validation.Input1", TableParameter::UINT32_TABLE, true},
  3716. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3717. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  3718. { L"Validation.Expected1", TableParameter::STRING_TABLE, true }
  3719. };
  3720. static TableParameter WaveIntrinsicsActiveIntParameters[] = {
  3721. { L"ShaderOp.Name", TableParameter::STRING, true },
  3722. { L"ShaderOp.Text", TableParameter::STRING, true },
  3723. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3724. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  3725. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  3726. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  3727. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  3728. };
  3729. static TableParameter WaveIntrinsicsPrefixIntParameters[] = {
  3730. { L"ShaderOp.Name", TableParameter::STRING, true },
  3731. { L"ShaderOp.Text", TableParameter::STRING, true },
  3732. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3733. { L"Validation.InputSet1", TableParameter::INT32_TABLE, true },
  3734. { L"Validation.InputSet2", TableParameter::INT32_TABLE, false },
  3735. { L"Validation.InputSet3", TableParameter::INT32_TABLE, false },
  3736. { L"Validation.InputSet4", TableParameter::INT32_TABLE, false }
  3737. };
  3738. static TableParameter WaveIntrinsicsActiveUintParameters[] = {
  3739. { L"ShaderOp.Name", TableParameter::STRING, true },
  3740. { L"ShaderOp.Text", TableParameter::STRING, true },
  3741. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3742. { L"Validation.InputSet1", TableParameter::UINT32_TABLE, true },
  3743. { L"Validation.InputSet2", TableParameter::UINT32_TABLE, false },
  3744. { L"Validation.InputSet3", TableParameter::UINT32_TABLE, false },
  3745. { L"Validation.InputSet4", TableParameter::UINT32_TABLE, false }
  3746. };
  3747. static TableParameter WaveIntrinsicsPrefixUintParameters[] = {
  3748. { L"ShaderOp.Name", TableParameter::STRING, true },
  3749. { L"ShaderOp.Text", TableParameter::STRING, true },
  3750. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3751. { L"Validation.InputSet1", TableParameter::UINT32_TABLE, true },
  3752. { L"Validation.InputSet2", TableParameter::UINT32_TABLE, false },
  3753. { L"Validation.InputSet3", TableParameter::UINT32_TABLE, false },
  3754. { L"Validation.InputSet4", TableParameter::UINT32_TABLE, false }
  3755. };
  3756. static TableParameter WaveIntrinsicsMultiPrefixIntParameters[] = {
  3757. { L"ShaderOp.Name", TableParameter::STRING, true },
  3758. { L"ShaderOp.Target", TableParameter::STRING, true },
  3759. { L"ShaderOp.Text", TableParameter::STRING, true },
  3760. { L"Validation.Keys", TableParameter::INT32_TABLE, true },
  3761. { L"Validation.Values", TableParameter::INT32_TABLE, true },
  3762. };
  3763. static TableParameter WaveIntrinsicsMultiPrefixUintParameters[] = {
  3764. { L"ShaderOp.Name", TableParameter::STRING, true },
  3765. { L"ShaderOp.Target", TableParameter::STRING, true },
  3766. { L"ShaderOp.Text", TableParameter::STRING, true },
  3767. { L"Validation.Keys", TableParameter::UINT32_TABLE, true },
  3768. { L"Validation.Values", TableParameter::UINT32_TABLE, true },
  3769. };
  3770. static TableParameter WaveIntrinsicsActiveBoolParameters[] = {
  3771. { L"ShaderOp.Name", TableParameter::STRING, true },
  3772. { L"ShaderOp.Text", TableParameter::STRING, true },
  3773. { L"Validation.NumInputSet", TableParameter::UINT, true },
  3774. { L"Validation.InputSet1", TableParameter::BOOL_TABLE, true },
  3775. { L"Validation.InputSet2", TableParameter::BOOL_TABLE, false },
  3776. { L"Validation.InputSet3", TableParameter::BOOL_TABLE, false },
  3777. };
  3778. static TableParameter CBufferTestHalfParameters[] = {
  3779. { L"Validation.InputSet", TableParameter::HALF_TABLE, true },
  3780. };
  3781. static TableParameter DenormBinaryFPOpParameters[] = {
  3782. { L"ShaderOp.Target", TableParameter::STRING, true },
  3783. { L"ShaderOp.Text", TableParameter::STRING, true },
  3784. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3785. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3786. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3787. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3788. { L"Validation.Expected2", TableParameter::STRING_TABLE, false },
  3789. { L"Validation.Type", TableParameter::STRING, true },
  3790. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3791. };
  3792. static TableParameter DenormTertiaryFPOpParameters[] = {
  3793. { L"ShaderOp.Target", TableParameter::STRING, true },
  3794. { L"ShaderOp.Text", TableParameter::STRING, true },
  3795. { L"ShaderOp.Arguments", TableParameter::STRING, true },
  3796. { L"Validation.Input1", TableParameter::STRING_TABLE, true },
  3797. { L"Validation.Input2", TableParameter::STRING_TABLE, true },
  3798. { L"Validation.Input3", TableParameter::STRING_TABLE, true },
  3799. { L"Validation.Expected1", TableParameter::STRING_TABLE, true },
  3800. { L"Validation.Expected2", TableParameter::STRING_TABLE, false },
  3801. { L"Validation.Type", TableParameter::STRING, true },
  3802. { L"Validation.Tolerance", TableParameter::DOUBLE, true },
  3803. };
  3804. static TableParameter PackUnpackOpParameters[] = {
  3805. { L"ShaderOp.Text", TableParameter::STRING, true },
  3806. { L"Validation.Type", TableParameter::STRING, true },
  3807. { L"Validation.Tolerance", TableParameter::UINT, true },
  3808. { L"Validation.Input", TableParameter::UINT32_TABLE, true },
  3809. };
  3810. static bool IsHexString(PCWSTR str, uint16_t *value) {
  3811. std::wstring wString(str);
  3812. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3813. LPCWSTR wstr = wString.c_str();
  3814. if (wcsncmp(wstr, L"0x", 2) == 0 || wcsncmp(wstr, L"0b", 2) == 0) {
  3815. *value = (uint16_t)wcstol(wstr, NULL, 0);
  3816. return true;
  3817. }
  3818. return false;
  3819. }
  3820. static HRESULT ParseDataToFloat(PCWSTR str, float &value) {
  3821. std::wstring wString(str);
  3822. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3823. PCWSTR wstr = wString.data();
  3824. if (_wcsicmp(wstr, L"NaN") == 0) {
  3825. value = NAN;
  3826. } else if (_wcsicmp(wstr, L"-inf") == 0) {
  3827. value = -(INFINITY);
  3828. } else if (_wcsicmp(wstr, L"inf") == 0) {
  3829. value = INFINITY;
  3830. } else if (_wcsicmp(wstr, L"-denorm") == 0) {
  3831. value = -(FLT_MIN / 2);
  3832. } else if (_wcsicmp(wstr, L"denorm") == 0) {
  3833. value = FLT_MIN / 2;
  3834. } else if (_wcsicmp(wstr, L"-0.0f") == 0 || _wcsicmp(wstr, L"-0.0") == 0 ||
  3835. _wcsicmp(wstr, L"-0") == 0) {
  3836. value = -0.0f;
  3837. } else if (_wcsicmp(wstr, L"0.0f") == 0 || _wcsicmp(wstr, L"0.0") == 0 ||
  3838. _wcsicmp(wstr, L"0") == 0) {
  3839. value = 0.0f;
  3840. } else if (_wcsnicmp(wstr, L"0x", 2) == 0) { // For hex values, take values literally
  3841. unsigned temp_i = std::stoul(wstr, nullptr, 16);
  3842. value = (float&)temp_i;
  3843. }
  3844. else {
  3845. // evaluate the expression of wstring
  3846. double val = _wtof(wstr);
  3847. if (val == 0) {
  3848. LogErrorFmt(L"Failed to parse parameter %s to float", wstr);
  3849. return E_FAIL;
  3850. }
  3851. value = (float)val;
  3852. }
  3853. return S_OK;
  3854. }
  3855. static HRESULT ParseDataToInt(PCWSTR str, int &value) {
  3856. std::wstring wString(str);
  3857. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3858. PCWSTR wstr = wString.data();
  3859. // evaluate the expression of string
  3860. if (_wcsicmp(wstr, L"0.0") == 0 || _wcsicmp(wstr, L"0") == 0) {
  3861. value = 0;
  3862. return S_OK;
  3863. }
  3864. int val = _wtoi(wstr);
  3865. if (val == 0) {
  3866. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  3867. return E_FAIL;
  3868. }
  3869. value = val;
  3870. return S_OK;
  3871. }
  3872. static HRESULT ParseDataToUint(PCWSTR str, unsigned int &value) {
  3873. std::wstring wString(str);
  3874. wString.erase(std::remove(wString.begin(), wString.end(), L' '), wString.end());
  3875. PCWSTR wstr = wString.data();
  3876. // evaluate the expression of string
  3877. if (_wcsicmp(wstr, L"0") == 0 || _wcsicmp(wstr, L"0x00000000") == 0) {
  3878. value = 0;
  3879. return S_OK;
  3880. }
  3881. wchar_t *end;
  3882. unsigned int val = std::wcstoul(wstr, &end, 0);
  3883. if (val == 0) {
  3884. LogErrorFmt(L"Failed to parse parameter %s to int", wstr);
  3885. return E_FAIL;
  3886. }
  3887. value = val;
  3888. return S_OK;
  3889. }
  3890. static HRESULT ParseDataToVectorFloat(PCWSTR str, float *ptr, size_t count) {
  3891. std::wstring wstr(str);
  3892. size_t curPosition = 0;
  3893. // parse a string of dot product separated by commas
  3894. for (size_t i = 0; i < count; ++i) {
  3895. size_t nextPosition = wstr.find(L",", curPosition);
  3896. if (FAILED(ParseDataToFloat(
  3897. wstr.substr(curPosition, nextPosition - curPosition).data(),
  3898. *(ptr + i)))) {
  3899. return E_FAIL;
  3900. }
  3901. curPosition = nextPosition + 1;
  3902. }
  3903. return S_OK;
  3904. }
  3905. static HRESULT ParseDataToVectorHalf(PCWSTR str, uint16_t *ptr, size_t count) {
  3906. std::wstring wstr(str);
  3907. size_t curPosition = 0;
  3908. // parse a string of dot product separated by commas
  3909. for (size_t i = 0; i < count; ++i) {
  3910. size_t nextPosition = wstr.find(L",", curPosition);
  3911. float floatValue;
  3912. if (FAILED(ParseDataToFloat(
  3913. wstr.substr(curPosition, nextPosition - curPosition).data(), floatValue))) {
  3914. return E_FAIL;
  3915. }
  3916. *(ptr + i) = ConvertFloat32ToFloat16(floatValue);
  3917. curPosition = nextPosition + 1;
  3918. }
  3919. return S_OK;
  3920. }
  3921. static HRESULT ParseDataToVectorUint(PCWSTR str, unsigned int *ptr, size_t count) {
  3922. std::wstring wstr(str);
  3923. size_t curPosition = 0;
  3924. // parse a string of dot product separated by commas
  3925. for (size_t i = 0; i < count; ++i) {
  3926. size_t nextPosition = wstr.find(L",", curPosition);
  3927. if (FAILED(ParseDataToUint(
  3928. wstr.substr(curPosition, nextPosition - curPosition).data(),
  3929. *(ptr + i)))) {
  3930. return E_FAIL;
  3931. }
  3932. curPosition = nextPosition + 1;
  3933. }
  3934. return S_OK;
  3935. }
  3936. HRESULT TableParameterHandler::ParseTableRow() {
  3937. TableParameter *table = m_table;
  3938. for (unsigned int i = 0; i < m_tableSize; ++i) {
  3939. switch (table[i].m_type) {
  3940. case TableParameter::INT8:
  3941. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3942. table[i].m_int32)) && table[i].m_required) {
  3943. // TryGetValue does not suppport reading from int16
  3944. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3945. return E_FAIL;
  3946. }
  3947. table[i].m_int8 = (int8_t)(table[i].m_int32);
  3948. break;
  3949. case TableParameter::INT16:
  3950. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3951. table[i].m_int32)) && table[i].m_required) {
  3952. // TryGetValue does not suppport reading from int16
  3953. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3954. return E_FAIL;
  3955. }
  3956. table[i].m_int16 = (short)(table[i].m_int32);
  3957. break;
  3958. case TableParameter::INT32:
  3959. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3960. table[i].m_int32)) && table[i].m_required) {
  3961. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3962. return E_FAIL;
  3963. }
  3964. break;
  3965. case TableParameter::UINT:
  3966. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3967. table[i].m_uint)) && table[i].m_required) {
  3968. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3969. return E_FAIL;
  3970. }
  3971. break;
  3972. case TableParameter::DOUBLE:
  3973. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3974. table[i].m_name, table[i].m_double)) && table[i].m_required) {
  3975. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3976. return E_FAIL;
  3977. }
  3978. break;
  3979. case TableParameter::STRING:
  3980. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3981. table[i].m_str)) && table[i].m_required) {
  3982. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3983. return E_FAIL;
  3984. }
  3985. break;
  3986. case TableParameter::BOOL:
  3987. if (FAILED(WEX::TestExecution::TestData::TryGetValue(table[i].m_name,
  3988. table[i].m_str)) && table[i].m_bool) {
  3989. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3990. return E_FAIL;
  3991. }
  3992. break;
  3993. case TableParameter::INT8_TABLE: {
  3994. WEX::TestExecution::TestDataArray<int> tempTable;
  3995. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  3996. table[i].m_name, tempTable)) && table[i].m_required) {
  3997. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  3998. return E_FAIL;
  3999. }
  4000. // TryGetValue does not suppport reading from int8
  4001. table[i].m_int8Table.resize(tempTable.GetSize());
  4002. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4003. table[i].m_int8Table[j] = (int8_t)tempTable[j];
  4004. }
  4005. break;
  4006. }
  4007. case TableParameter::INT16_TABLE: {
  4008. WEX::TestExecution::TestDataArray<int> tempTable;
  4009. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4010. table[i].m_name, tempTable)) && table[i].m_required) {
  4011. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4012. return E_FAIL;
  4013. }
  4014. // TryGetValue does not suppport reading from int8
  4015. table[i].m_int16Table.resize(tempTable.GetSize());
  4016. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4017. table[i].m_int16Table[j] = (int16_t)tempTable[j];
  4018. }
  4019. break;
  4020. }case TableParameter::INT32_TABLE: {
  4021. WEX::TestExecution::TestDataArray<int> tempTable;
  4022. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4023. table[i].m_name, tempTable)) && table[i].m_required) {
  4024. // TryGetValue does not suppport reading from int8
  4025. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4026. return E_FAIL;
  4027. }
  4028. table[i].m_int32Table.resize(tempTable.GetSize());
  4029. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4030. table[i].m_int32Table[j] = tempTable[j];
  4031. }
  4032. break;
  4033. }
  4034. case TableParameter::UINT8_TABLE: {
  4035. WEX::TestExecution::TestDataArray<int> tempTable;
  4036. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4037. table[i].m_name, tempTable)) && table[i].m_required) {
  4038. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4039. return E_FAIL;
  4040. }
  4041. // TryGetValue does not suppport reading from int8
  4042. table[i].m_int8Table.resize(tempTable.GetSize());
  4043. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4044. table[i].m_int8Table[j] = (uint8_t)tempTable[j];
  4045. }
  4046. break;
  4047. }
  4048. case TableParameter::UINT16_TABLE: {
  4049. WEX::TestExecution::TestDataArray<int> tempTable;
  4050. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4051. table[i].m_name, tempTable)) && table[i].m_required) {
  4052. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4053. return E_FAIL;
  4054. }
  4055. // TryGetValue does not suppport reading from int8
  4056. table[i].m_uint16Table.resize(tempTable.GetSize());
  4057. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4058. table[i].m_uint16Table[j] = (uint16_t)tempTable[j];
  4059. }
  4060. break;
  4061. }
  4062. case TableParameter::UINT32_TABLE: {
  4063. WEX::TestExecution::TestDataArray<unsigned int> tempTable;
  4064. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4065. table[i].m_name, tempTable)) && table[i].m_required) {
  4066. // TryGetValue does not suppport reading from int8
  4067. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4068. return E_FAIL;
  4069. }
  4070. table[i].m_uint32Table.resize(tempTable.GetSize());
  4071. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4072. table[i].m_uint32Table[j] = tempTable[j];
  4073. }
  4074. break;
  4075. }
  4076. case TableParameter::FLOAT_TABLE: {
  4077. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4078. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4079. table[i].m_name, tempTable)) && table[i].m_required) {
  4080. // TryGetValue does not suppport reading from int8
  4081. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4082. return E_FAIL;
  4083. }
  4084. table[i].m_floatTable.resize(tempTable.GetSize());
  4085. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4086. ParseDataToFloat(tempTable[j], table[i].m_floatTable[j]);
  4087. }
  4088. break;
  4089. }
  4090. case TableParameter::HALF_TABLE: {
  4091. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4092. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4093. table[i].m_name, tempTable)) && table[i].m_required) {
  4094. // TryGetValue does not suppport reading from int8
  4095. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4096. return E_FAIL;
  4097. }
  4098. table[i].m_halfTable.resize(tempTable.GetSize());
  4099. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4100. uint16_t value = 0;
  4101. if (IsHexString(tempTable[j], &value)) {
  4102. table[i].m_halfTable[j] = value;
  4103. }
  4104. else {
  4105. float val;
  4106. ParseDataToFloat(tempTable[j], val);
  4107. if (isdenorm(val))
  4108. table[i].m_halfTable[j] = signbit(val) ? Float16NegDenorm : Float16PosDenorm;
  4109. else
  4110. table[i].m_halfTable[j] = ConvertFloat32ToFloat16(val);
  4111. }
  4112. }
  4113. break;
  4114. }
  4115. case TableParameter::DOUBLE_TABLE: {
  4116. WEX::TestExecution::TestDataArray<double> tempTable;
  4117. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4118. table[i].m_name, tempTable)) && table[i].m_required) {
  4119. // TryGetValue does not suppport reading from int8
  4120. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4121. return E_FAIL;
  4122. }
  4123. table[i].m_doubleTable.resize(tempTable.GetSize());
  4124. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4125. table[i].m_doubleTable[j] = tempTable[j];
  4126. }
  4127. break;
  4128. }
  4129. case TableParameter::BOOL_TABLE: {
  4130. WEX::TestExecution::TestDataArray<bool> tempTable;
  4131. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4132. table[i].m_name, tempTable)) && table[i].m_required) {
  4133. // TryGetValue does not suppport reading from int8
  4134. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4135. return E_FAIL;
  4136. }
  4137. table[i].m_boolTable.resize(tempTable.GetSize());
  4138. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4139. table[i].m_boolTable[j] = tempTable[j];
  4140. }
  4141. break;
  4142. }
  4143. case TableParameter::STRING_TABLE: {
  4144. WEX::TestExecution::TestDataArray<WEX::Common::String> tempTable;
  4145. if (FAILED(WEX::TestExecution::TestData::TryGetValue(
  4146. table[i].m_name, tempTable)) && table[i].m_required) {
  4147. // TryGetValue does not suppport reading from int8
  4148. LogErrorFmt(L"Failed to get %s", table[i].m_name);
  4149. return E_FAIL;
  4150. }
  4151. table[i].m_StringTable.resize(tempTable.GetSize());
  4152. for (size_t j = 0, end = tempTable.GetSize(); j != end; ++j) {
  4153. table[i].m_StringTable[j] = tempTable[j];
  4154. }
  4155. break;
  4156. }
  4157. default:
  4158. DXASSERT_NOMSG("Invalid Parameter Type");
  4159. }
  4160. if (errno == ERANGE) {
  4161. LogErrorFmt(L"got out of range value for table %s", table[i].m_name);
  4162. return E_FAIL;
  4163. }
  4164. }
  4165. return S_OK;
  4166. }
  4167. static void VerifyOutputWithExpectedValueInt(int output, int ref, int tolerance) {
  4168. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  4169. }
  4170. static void VerifyOutputWithExpectedValueUInt(uint32_t output, uint32_t ref, uint32_t tolerance) {
  4171. VERIFY_IS_TRUE(output - ref <= tolerance && ref - output <= tolerance);
  4172. }
  4173. static void VerifyOutputWithExpectedValueUInt4(XMUINT4 output, XMUINT4 ref) {
  4174. VERIFY_ARE_EQUAL(output.x, ref.x);
  4175. VERIFY_ARE_EQUAL(output.y, ref.y);
  4176. VERIFY_ARE_EQUAL(output.z, ref.z);
  4177. VERIFY_ARE_EQUAL(output.w, ref.w);
  4178. }
  4179. static void VerifyOutputWithExpectedValueFloat(
  4180. float output, float ref, LPCWSTR type, double tolerance,
  4181. hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) {
  4182. if (_wcsicmp(type, L"Relative") == 0) {
  4183. VERIFY_IS_TRUE(CompareFloatRelativeEpsilon(output, ref, (int)tolerance, mode));
  4184. } else if (_wcsicmp(type, L"Epsilon") == 0) {
  4185. VERIFY_IS_TRUE(CompareFloatEpsilon(output, ref, (float)tolerance, mode));
  4186. } else if (_wcsicmp(type, L"ULP") == 0) {
  4187. VERIFY_IS_TRUE(CompareFloatULP(output, ref, (int)tolerance, mode));
  4188. } else {
  4189. LogErrorFmt(L"Failed to read comparison type %S", type);
  4190. }
  4191. }
  4192. static bool CompareOutputWithExpectedValueFloat(
  4193. float output, float ref, LPCWSTR type, double tolerance,
  4194. hlsl::DXIL::Float32DenormMode mode = hlsl::DXIL::Float32DenormMode::Any) {
  4195. if (_wcsicmp(type, L"Relative") == 0) {
  4196. return CompareFloatRelativeEpsilon(output, ref, (int)tolerance, mode);
  4197. } else if (_wcsicmp(type, L"Epsilon") == 0) {
  4198. return CompareFloatEpsilon(output, ref, (float)tolerance, mode);
  4199. } else if (_wcsicmp(type, L"ULP") == 0) {
  4200. return CompareFloatULP(output, ref, (int)tolerance, mode);
  4201. } else {
  4202. LogErrorFmt(L"Failed to read comparison type %S", type);
  4203. return false;
  4204. }
  4205. }
  4206. static void VerifyOutputWithExpectedValueHalf(
  4207. uint16_t output, uint16_t ref, LPCWSTR type, double tolerance) {
  4208. if (_wcsicmp(type, L"Relative") == 0) {
  4209. VERIFY_IS_TRUE(CompareHalfRelativeEpsilon(output, ref, (int)tolerance));
  4210. }
  4211. else if (_wcsicmp(type, L"Epsilon") == 0) {
  4212. VERIFY_IS_TRUE(CompareHalfEpsilon(output, ref, (float)tolerance));
  4213. }
  4214. else if (_wcsicmp(type, L"ULP") == 0) {
  4215. VERIFY_IS_TRUE(CompareHalfULP(output, ref, (float)tolerance));
  4216. }
  4217. else {
  4218. LogErrorFmt(L"Failed to read comparison type %S", type);
  4219. }
  4220. }
  4221. TEST_F(ExecutionTest, UnaryFloatOpTest) {
  4222. WEX::TestExecution::SetVerifyOutput verifySettings(
  4223. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4224. CComPtr<IStream> pStream;
  4225. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4226. CComPtr<ID3D12Device> pDevice;
  4227. if (!CreateDevice(&pDevice)) {
  4228. return;
  4229. }
  4230. // Read data from the table
  4231. int tableSize = sizeof(UnaryFPOpParameters) / sizeof(TableParameter);
  4232. TableParameterHandler handler(UnaryFPOpParameters, tableSize);
  4233. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4234. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4235. unsigned int WarpVersion = handler.GetTableParamByName(L"Warp.Version")->m_uint;
  4236. if (GetTestParamUseWARP(true) && !IsValidWarpDllVersion(WarpVersion)) {
  4237. return;
  4238. }
  4239. std::vector<float> *Validation_Input =
  4240. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4241. std::vector<float> *Validation_Expected =
  4242. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4243. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4244. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4245. size_t count = Validation_Input->size();
  4246. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4247. pDevice, m_support, pStream, "UnaryFPOp",
  4248. // this callbacked is called when the test
  4249. // is creating the resource to run the test
  4250. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4251. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  4252. size_t size = sizeof(SUnaryFPOp) * count;
  4253. Data.resize(size);
  4254. SUnaryFPOp *pPrimitives = (SUnaryFPOp *)Data.data();
  4255. for (size_t i = 0; i < count; ++i) {
  4256. SUnaryFPOp *p = &pPrimitives[i];
  4257. p->input = (*Validation_Input)[i % Validation_Input->size()];
  4258. }
  4259. // use shader from data table
  4260. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4261. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4262. });
  4263. MappedData data;
  4264. test->Test->GetReadBackData("SUnaryFPOp", &data);
  4265. SUnaryFPOp *pPrimitives = (SUnaryFPOp*)data.data();
  4266. WEX::TestExecution::DisableVerifyExceptions dve;
  4267. for (unsigned i = 0; i < count; ++i) {
  4268. SUnaryFPOp *p = &pPrimitives[i];
  4269. float val = (*Validation_Expected)[i % Validation_Expected->size()];
  4270. LogCommentFmt(
  4271. L"element #%u, input = %6.8f, output = %6.8f, expected = %6.8f", i,
  4272. p->input, p->output, val);
  4273. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type, Validation_Tolerance);
  4274. }
  4275. }
  4276. TEST_F(ExecutionTest, BinaryFloatOpTest) {
  4277. WEX::TestExecution::SetVerifyOutput verifySettings(
  4278. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4279. CComPtr<IStream> pStream;
  4280. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4281. CComPtr<ID3D12Device> pDevice;
  4282. if (!CreateDevice(&pDevice)) {
  4283. return;
  4284. }
  4285. // Read data from the table
  4286. int tableSize = sizeof(BinaryFPOpParameters) / sizeof(TableParameter);
  4287. TableParameterHandler handler(BinaryFPOpParameters, tableSize);
  4288. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4289. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4290. std::vector<float> *Validation_Input1 =
  4291. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4292. std::vector<float> *Validation_Input2 =
  4293. &(handler.GetTableParamByName(L"Validation.Input2")->m_floatTable);
  4294. std::vector<float> *Validation_Expected1 =
  4295. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4296. std::vector<float> *Validation_Expected2 =
  4297. &(handler.GetTableParamByName(L"Validation.Expected2")->m_floatTable);
  4298. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4299. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4300. size_t count = Validation_Input1->size();
  4301. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4302. pDevice, m_support, pStream, "BinaryFPOp",
  4303. // this callbacked is called when the test
  4304. // is creating the resource to run the test
  4305. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4306. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  4307. size_t size = sizeof(SBinaryFPOp) * count;
  4308. Data.resize(size);
  4309. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  4310. for (size_t i = 0; i < count; ++i) {
  4311. SBinaryFPOp *p = &pPrimitives[i];
  4312. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4313. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4314. }
  4315. // use shader from data table
  4316. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4317. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4318. });
  4319. MappedData data;
  4320. test->Test->GetReadBackData("SBinaryFPOp", &data);
  4321. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  4322. WEX::TestExecution::DisableVerifyExceptions dve;
  4323. unsigned numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4324. if (numExpected == 2) {
  4325. for (unsigned i = 0; i < count; ++i) {
  4326. SBinaryFPOp *p = &pPrimitives[i];
  4327. float val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4328. float val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4329. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  4330. L"%6.8f, expected1 = %6.8f, output2 = %6.8f, expected2 = %6.8f",
  4331. i, p->input1, p->input2, p->output1, val1, p->output2,
  4332. val2);
  4333. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  4334. Validation_Tolerance);
  4335. VerifyOutputWithExpectedValueFloat(p->output2, val2, Validation_Type,
  4336. Validation_Tolerance);
  4337. }
  4338. }
  4339. else if (numExpected == 1) {
  4340. for (unsigned i = 0; i < count; ++i) {
  4341. SBinaryFPOp *p = &pPrimitives[i];
  4342. float val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4343. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output1 = "
  4344. L"%6.8f, expected1 = %6.8f",
  4345. i, p->input1, p->input2, p->output1, val1);
  4346. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  4347. Validation_Tolerance);
  4348. }
  4349. }
  4350. else {
  4351. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4352. }
  4353. }
  4354. TEST_F(ExecutionTest, TertiaryFloatOpTest) {
  4355. WEX::TestExecution::SetVerifyOutput verifySettings(
  4356. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4357. CComPtr<IStream> pStream;
  4358. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4359. CComPtr<ID3D12Device> pDevice;
  4360. if (!CreateDevice(&pDevice)) {
  4361. return;
  4362. }
  4363. // Read data from the table
  4364. int tableSize = sizeof(TertiaryFPOpParameters) / sizeof(TableParameter);
  4365. TableParameterHandler handler(TertiaryFPOpParameters, tableSize);
  4366. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4367. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4368. std::vector<float> *Validation_Input1 =
  4369. &(handler.GetTableParamByName(L"Validation.Input1")->m_floatTable);
  4370. std::vector<float> *Validation_Input2 =
  4371. &(handler.GetTableParamByName(L"Validation.Input2")->m_floatTable);
  4372. std::vector<float> *Validation_Input3 =
  4373. &(handler.GetTableParamByName(L"Validation.Input3")->m_floatTable);
  4374. std::vector<float> *Validation_Expected =
  4375. &(handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable);
  4376. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4377. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4378. size_t count = Validation_Input1->size();
  4379. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4380. pDevice, m_support, pStream, "TertiaryFPOp",
  4381. // this callbacked is called when the test
  4382. // is creating the resource to run the test
  4383. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4384. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  4385. size_t size = sizeof(STertiaryFPOp) * count;
  4386. Data.resize(size);
  4387. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  4388. for (size_t i = 0; i < count; ++i) {
  4389. STertiaryFPOp *p = &pPrimitives[i];
  4390. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4391. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4392. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4393. }
  4394. // use shader from data table
  4395. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4396. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4397. });
  4398. MappedData data;
  4399. test->Test->GetReadBackData("STertiaryFPOp", &data);
  4400. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  4401. WEX::TestExecution::DisableVerifyExceptions dve;
  4402. for (unsigned i = 0; i < count; ++i) {
  4403. STertiaryFPOp *p = &pPrimitives[i];
  4404. float val = (*Validation_Expected)[i % Validation_Expected->size()];
  4405. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output1 = "
  4406. L"%6.8f, expected = %6.8f",
  4407. i, p->input1, p->input2, p->input3, p->output, val);
  4408. VerifyOutputWithExpectedValueFloat(p->output, val, Validation_Type,
  4409. Validation_Tolerance);
  4410. }
  4411. }
  4412. TEST_F(ExecutionTest, UnaryHalfOpTest) {
  4413. WEX::TestExecution::SetVerifyOutput verifySettings(
  4414. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4415. CComPtr<IStream> pStream;
  4416. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4417. CComPtr<ID3D12Device> pDevice;
  4418. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4419. return;
  4420. }
  4421. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4422. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4423. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4424. return;
  4425. }
  4426. // Read data from the table
  4427. int tableSize = sizeof(UnaryHalfOpParameters) / sizeof(TableParameter);
  4428. TableParameterHandler handler(UnaryHalfOpParameters, tableSize);
  4429. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4430. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4431. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4432. unsigned int WarpVersion = handler.GetTableParamByName(L"Warp.Version")->m_uint;
  4433. if (GetTestParamUseWARP(true) && !IsValidWarpDllVersion(WarpVersion)) {
  4434. return;
  4435. }
  4436. std::vector<uint16_t> *Validation_Input =
  4437. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4438. std::vector<uint16_t> *Validation_Expected =
  4439. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4440. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4441. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4442. size_t count = Validation_Input->size();
  4443. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4444. pDevice, m_support, pStream, "UnaryFPOp",
  4445. // this callbacked is called when the test
  4446. // is creating the resource to run the test
  4447. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4448. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryFPOp"));
  4449. size_t size = sizeof(SUnaryHalfOp) * count;
  4450. Data.resize(size);
  4451. SUnaryHalfOp *pPrimitives = (SUnaryHalfOp *)Data.data();
  4452. for (size_t i = 0; i < count; ++i) {
  4453. SUnaryHalfOp *p = &pPrimitives[i];
  4454. p->input = (*Validation_Input)[i % Validation_Input->size()];
  4455. }
  4456. // use shader from data table
  4457. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4458. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4459. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4460. });
  4461. MappedData data;
  4462. test->Test->GetReadBackData("SUnaryFPOp", &data);
  4463. SUnaryHalfOp *pPrimitives = (SUnaryHalfOp*)data.data();
  4464. WEX::TestExecution::DisableVerifyExceptions dve;
  4465. for (unsigned i = 0; i < count; ++i) {
  4466. SUnaryHalfOp *p = &pPrimitives[i];
  4467. uint16_t expected = (*Validation_Expected)[i % Validation_Input->size()];
  4468. LogCommentFmt(L"element #%u, input = %6.8f(0x%04x), output = "
  4469. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4470. i, ConvertFloat16ToFloat32(p->input), p->input,
  4471. ConvertFloat16ToFloat32(p->output), p->output,
  4472. ConvertFloat16ToFloat32(expected), expected);
  4473. VerifyOutputWithExpectedValueHalf(p->output, expected, Validation_Type, Validation_Tolerance);
  4474. }
  4475. }
  4476. TEST_F(ExecutionTest, BinaryHalfOpTest) {
  4477. WEX::TestExecution::SetVerifyOutput verifySettings(
  4478. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4479. CComPtr<IStream> pStream;
  4480. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4481. CComPtr<ID3D12Device> pDevice;
  4482. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4483. return;
  4484. }
  4485. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4486. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4487. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4488. return;
  4489. }
  4490. // Read data from the table
  4491. int tableSize = sizeof(BinaryHalfOpParameters) / sizeof(TableParameter);
  4492. TableParameterHandler handler(BinaryHalfOpParameters, tableSize);
  4493. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4494. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4495. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4496. std::vector<uint16_t> *Validation_Input1 =
  4497. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4498. std::vector<uint16_t> *Validation_Input2 =
  4499. &(handler.GetTableParamByName(L"Validation.Input2")->m_halfTable);
  4500. std::vector<uint16_t> *Validation_Expected1 =
  4501. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4502. std::vector<uint16_t> *Validation_Expected2 =
  4503. &(handler.GetTableParamByName(L"Validation.Expected2")->m_halfTable);
  4504. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4505. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4506. size_t count = Validation_Input1->size();
  4507. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4508. pDevice, m_support, pStream, "BinaryFPOp",
  4509. // this callbacked is called when the test
  4510. // is creating the resource to run the test
  4511. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4512. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  4513. size_t size = sizeof(SBinaryHalfOp) * count;
  4514. Data.resize(size);
  4515. SBinaryHalfOp *pPrimitives = (SBinaryHalfOp *)Data.data();
  4516. for (size_t i = 0; i < count; ++i) {
  4517. SBinaryHalfOp *p = &pPrimitives[i];
  4518. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4519. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4520. }
  4521. // use shader from data table
  4522. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4523. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4524. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4525. });
  4526. MappedData data;
  4527. test->Test->GetReadBackData("SBinaryFPOp", &data);
  4528. SBinaryHalfOp *pPrimitives = (SBinaryHalfOp *)data.data();
  4529. WEX::TestExecution::DisableVerifyExceptions dve;
  4530. unsigned numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4531. if (numExpected == 2) {
  4532. for (unsigned i = 0; i < count; ++i) {
  4533. SBinaryHalfOp *p = &pPrimitives[i];
  4534. uint16_t expected1 = (*Validation_Expected1)[i % Validation_Input1->size()];
  4535. uint16_t expected2 = (*Validation_Expected2)[i % Validation_Input2->size()];
  4536. LogCommentFmt(L"element #%u, input1 = %6.8f(0x%04x), input2 = %6.8f(0x%04x), output1 = "
  4537. L"%6.8f(0x%04x), expected1 = %6.8f(0x%04x), output2 = %6.8f(0x%04x), expected2 = %6.8f(0x%04x)",
  4538. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4539. ConvertFloat16ToFloat32(p->input2), p->input2,
  4540. ConvertFloat16ToFloat32(p->output1), p->output1,
  4541. ConvertFloat16ToFloat32(p->output2), p->output2,
  4542. ConvertFloat16ToFloat32(expected1), expected1,
  4543. ConvertFloat16ToFloat32(expected2), expected2);
  4544. VerifyOutputWithExpectedValueHalf(p->output1, expected1, Validation_Type, Validation_Tolerance);
  4545. VerifyOutputWithExpectedValueHalf(p->output2, expected2, Validation_Type, Validation_Tolerance);
  4546. }
  4547. }
  4548. else if (numExpected == 1) {
  4549. for (unsigned i = 0; i < count; ++i) {
  4550. uint16_t expected = (*Validation_Expected1)[i % Validation_Input1->size()];
  4551. SBinaryHalfOp *p = &pPrimitives[i];
  4552. LogCommentFmt(L"element #%u, input = %6.8f(0x%04x), output = "
  4553. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4554. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4555. ConvertFloat16ToFloat32(p->output1), p->output1,
  4556. ConvertFloat16ToFloat32(expected), expected);
  4557. VerifyOutputWithExpectedValueHalf(p->output1, expected, Validation_Type, Validation_Tolerance);
  4558. }
  4559. }
  4560. else {
  4561. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4562. }
  4563. }
  4564. TEST_F(ExecutionTest, TertiaryHalfOpTest) {
  4565. WEX::TestExecution::SetVerifyOutput verifySettings(
  4566. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4567. CComPtr<IStream> pStream;
  4568. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4569. CComPtr<ID3D12Device> pDevice;
  4570. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  4571. return;
  4572. }
  4573. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  4574. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  4575. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  4576. return;
  4577. }
  4578. // Read data from the table
  4579. int tableSize = sizeof(TertiaryHalfOpParameters) / sizeof(TableParameter);
  4580. TableParameterHandler handler(TertiaryHalfOpParameters, tableSize);
  4581. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4582. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4583. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  4584. std::vector<uint16_t> *Validation_Input1 =
  4585. &(handler.GetTableParamByName(L"Validation.Input1")->m_halfTable);
  4586. std::vector<uint16_t> *Validation_Input2 =
  4587. &(handler.GetTableParamByName(L"Validation.Input2")->m_halfTable);
  4588. std::vector<uint16_t> *Validation_Input3 =
  4589. &(handler.GetTableParamByName(L"Validation.Input3")->m_halfTable);
  4590. std::vector<uint16_t> *Validation_Expected =
  4591. &(handler.GetTableParamByName(L"Validation.Expected1")->m_halfTable);
  4592. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  4593. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  4594. size_t count = Validation_Input1->size();
  4595. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4596. pDevice, m_support, pStream, "TertiaryFPOp",
  4597. // this callbacked is called when the test
  4598. // is creating the resource to run the test
  4599. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4600. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  4601. size_t size = sizeof(STertiaryHalfOp) * count;
  4602. Data.resize(size);
  4603. STertiaryHalfOp *pPrimitives = (STertiaryHalfOp *)Data.data();
  4604. for (size_t i = 0; i < count; ++i) {
  4605. STertiaryHalfOp *p = &pPrimitives[i];
  4606. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4607. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4608. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4609. }
  4610. // use shader from data table
  4611. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4612. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4613. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  4614. });
  4615. MappedData data;
  4616. test->Test->GetReadBackData("STertiaryFPOp", &data);
  4617. STertiaryHalfOp *pPrimitives = (STertiaryHalfOp *)data.data();
  4618. WEX::TestExecution::DisableVerifyExceptions dve;
  4619. for (unsigned i = 0; i < count; ++i) {
  4620. STertiaryHalfOp *p = &pPrimitives[i];
  4621. uint16_t expected = (*Validation_Expected)[i % Validation_Expected->size()];
  4622. LogCommentFmt(L"element #%u, input1 = %6.8f(0x%04x), input2 = %6.8f(0x%04x), input3 = %6.8f(0x%04x), output = "
  4623. L"%6.8f(0x%04x), expected = %6.8f(0x%04x)",
  4624. i, ConvertFloat16ToFloat32(p->input1), p->input1,
  4625. ConvertFloat16ToFloat32(p->input2), p->input2,
  4626. ConvertFloat16ToFloat32(p->input3), p->input3,
  4627. ConvertFloat16ToFloat32(p->output), p->output,
  4628. ConvertFloat16ToFloat32(expected), expected);
  4629. VerifyOutputWithExpectedValueHalf(p->output, expected, Validation_Type, Validation_Tolerance);
  4630. }
  4631. }
  4632. TEST_F(ExecutionTest, UnaryIntOpTest) {
  4633. WEX::TestExecution::SetVerifyOutput verifySettings(
  4634. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4635. CComPtr<IStream> pStream;
  4636. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4637. CComPtr<ID3D12Device> pDevice;
  4638. if (!CreateDevice(&pDevice)) {
  4639. return;
  4640. }
  4641. // Read data from the table
  4642. int tableSize = sizeof(UnaryIntOpParameters) / sizeof(TableParameter);
  4643. TableParameterHandler handler(UnaryIntOpParameters, tableSize);
  4644. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4645. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4646. std::vector<int> *Validation_Input =
  4647. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4648. std::vector<int> *Validation_Expected =
  4649. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4650. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4651. size_t count = Validation_Input->size();
  4652. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4653. pDevice, m_support, pStream, "UnaryIntOp",
  4654. // this callbacked is called when the test
  4655. // is creating the resource to run the test
  4656. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4657. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  4658. size_t size = sizeof(SUnaryIntOp) * count;
  4659. Data.resize(size);
  4660. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)Data.data();
  4661. for (size_t i = 0; i < count; ++i) {
  4662. SUnaryIntOp *p = &pPrimitives[i];
  4663. int val = (*Validation_Input)[i % Validation_Input->size()];
  4664. p->input = val;
  4665. }
  4666. // use shader data table
  4667. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4668. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4669. });
  4670. MappedData data;
  4671. test->Test->GetReadBackData("SUnaryIntOp", &data);
  4672. SUnaryIntOp *pPrimitives = (SUnaryIntOp *)data.data();
  4673. WEX::TestExecution::DisableVerifyExceptions dve;
  4674. for (unsigned i = 0; i < count; ++i) {
  4675. SUnaryIntOp *p = &pPrimitives[i];
  4676. int val = (*Validation_Expected)[i % Validation_Expected->size()];
  4677. LogCommentFmt(L"element #%u, input = %11i(0x%08x), output = %11i(0x%08x), "
  4678. L"expected = %11i(0x%08x)",
  4679. i, p->input, p->input, p->output, p->output, val, val);
  4680. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  4681. }
  4682. }
  4683. TEST_F(ExecutionTest, UnaryUintOpTest) {
  4684. WEX::TestExecution::SetVerifyOutput verifySettings(
  4685. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4686. CComPtr<IStream> pStream;
  4687. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4688. CComPtr<ID3D12Device> pDevice;
  4689. if (!CreateDevice(&pDevice)) {
  4690. return;
  4691. }
  4692. // Read data from the table
  4693. int tableSize = sizeof(UnaryUintOpParameters) / sizeof(TableParameter);
  4694. TableParameterHandler handler(UnaryUintOpParameters, tableSize);
  4695. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4696. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4697. std::vector<unsigned int> *Validation_Input =
  4698. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4699. std::vector<unsigned int> *Validation_Expected =
  4700. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4701. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4702. size_t count = Validation_Input->size();
  4703. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4704. pDevice, m_support, pStream, "UnaryUintOp",
  4705. // this callbacked is called when the test
  4706. // is creating the resource to run the test
  4707. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4708. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  4709. size_t size = sizeof(SUnaryUintOp) * count;
  4710. Data.resize(size);
  4711. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)Data.data();
  4712. for (size_t i = 0; i < count; ++i) {
  4713. SUnaryUintOp *p = &pPrimitives[i];
  4714. unsigned int val = (*Validation_Input)[i % Validation_Input->size()];
  4715. p->input = val;
  4716. }
  4717. // use shader data table
  4718. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4719. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4720. });
  4721. MappedData data;
  4722. test->Test->GetReadBackData("SUnaryUintOp", &data);
  4723. SUnaryUintOp *pPrimitives = (SUnaryUintOp *)data.data();
  4724. WEX::TestExecution::DisableVerifyExceptions dve;
  4725. for (unsigned i = 0; i < count; ++i) {
  4726. SUnaryUintOp *p = &pPrimitives[i];
  4727. unsigned int val = (*Validation_Expected)[i % Validation_Expected->size()];
  4728. LogCommentFmt(L"element #%u, input = %11u(0x%08x), output = %11u(0x%08x), "
  4729. L"expected = %11u(0x%08x)",
  4730. i, p->input, p->input, p->output, p->output, val, val);
  4731. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  4732. }
  4733. }
  4734. TEST_F(ExecutionTest, BinaryIntOpTest) {
  4735. WEX::TestExecution::SetVerifyOutput verifySettings(
  4736. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4737. CComPtr<IStream> pStream;
  4738. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4739. CComPtr<ID3D12Device> pDevice;
  4740. if (!CreateDevice(&pDevice)) {
  4741. return;
  4742. }
  4743. // Read data from the table
  4744. size_t tableSize = sizeof(BinaryIntOpParameters) / sizeof(TableParameter);
  4745. TableParameterHandler handler(BinaryIntOpParameters, tableSize);
  4746. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4747. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4748. std::vector<int> *Validation_Input1 =
  4749. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4750. std::vector<int> *Validation_Input2 =
  4751. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  4752. std::vector<int> *Validation_Expected1 =
  4753. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4754. std::vector<int> *Validation_Expected2 =
  4755. &handler.GetTableParamByName(L"Validation.Expected2")->m_int32Table;
  4756. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4757. size_t count = Validation_Input1->size();
  4758. size_t numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4759. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4760. pDevice, m_support, pStream, "BinaryIntOp",
  4761. // this callbacked is called when the test
  4762. // is creating the resource to run the test
  4763. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4764. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  4765. size_t size = sizeof(SBinaryIntOp) * count;
  4766. Data.resize(size);
  4767. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)Data.data();
  4768. for (size_t i = 0; i < count; ++i) {
  4769. SBinaryIntOp *p = &pPrimitives[i];
  4770. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4771. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4772. p->input1 = val1;
  4773. p->input2 = val2;
  4774. }
  4775. // use shader from data table
  4776. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4777. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4778. });
  4779. MappedData data;
  4780. test->Test->GetReadBackData("SBinaryIntOp", &data);
  4781. SBinaryIntOp *pPrimitives = (SBinaryIntOp *)data.data();
  4782. WEX::TestExecution::DisableVerifyExceptions dve;
  4783. if (numExpected == 2) {
  4784. for (unsigned i = 0; i < count; ++i) {
  4785. SBinaryIntOp *p = &pPrimitives[i];
  4786. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4787. int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4788. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4789. L"%11i(0x%08x), output1 = "
  4790. L"%11i(0x%08x), expected1 = %11i(0x%08x), output2 = "
  4791. L"%11i(0x%08x), expected2 = %11i(0x%08x)",
  4792. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  4793. p->output1, val1, val1, p->output2, p->output2, val2,
  4794. val2);
  4795. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4796. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  4797. }
  4798. }
  4799. else if (numExpected == 1) {
  4800. for (unsigned i = 0; i < count; ++i) {
  4801. SBinaryIntOp *p = &pPrimitives[i];
  4802. int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4803. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4804. L"%11i(0x%08x), output = "
  4805. L"%11i(0x%08x), expected = %11i(0x%08x)", i,
  4806. p->input1, p->input1, p->input2, p->input2,
  4807. p->output1, p->output1, val1, val1);
  4808. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4809. }
  4810. }
  4811. else {
  4812. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4813. }
  4814. }
  4815. TEST_F(ExecutionTest, TertiaryIntOpTest) {
  4816. WEX::TestExecution::SetVerifyOutput verifySettings(
  4817. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4818. CComPtr<IStream> pStream;
  4819. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4820. CComPtr<ID3D12Device> pDevice;
  4821. if (!CreateDevice(&pDevice)) {
  4822. return;
  4823. }
  4824. // Read data from the table
  4825. size_t tableSize = sizeof(TertiaryIntOpParameters) / sizeof(TableParameter);
  4826. TableParameterHandler handler(TertiaryIntOpParameters, tableSize);
  4827. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4828. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4829. std::vector<int> *Validation_Input1 =
  4830. &handler.GetTableParamByName(L"Validation.Input1")->m_int32Table;
  4831. std::vector<int> *Validation_Input2 =
  4832. &handler.GetTableParamByName(L"Validation.Input2")->m_int32Table;
  4833. std::vector<int> *Validation_Input3 =
  4834. &handler.GetTableParamByName(L"Validation.Input3")->m_int32Table;
  4835. std::vector<int> *Validation_Expected =
  4836. &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  4837. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4838. size_t count = Validation_Input1->size();
  4839. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4840. pDevice, m_support, pStream, "TertiaryIntOp",
  4841. // this callbacked is called when the test
  4842. // is creating the resource to run the test
  4843. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4844. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  4845. size_t size = sizeof(STertiaryIntOp) * count;
  4846. Data.resize(size);
  4847. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)Data.data();
  4848. for (size_t i = 0; i < count; ++i) {
  4849. STertiaryIntOp *p = &pPrimitives[i];
  4850. int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4851. int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4852. int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4853. p->input1 = val1;
  4854. p->input2 = val2;
  4855. p->input3 = val3;
  4856. }
  4857. // use shader from data table
  4858. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4859. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4860. });
  4861. MappedData data;
  4862. test->Test->GetReadBackData("STertiaryIntOp", &data);
  4863. STertiaryIntOp *pPrimitives = (STertiaryIntOp *)data.data();
  4864. WEX::TestExecution::DisableVerifyExceptions dve;
  4865. for (unsigned i = 0; i < count; ++i) {
  4866. STertiaryIntOp *p = &pPrimitives[i];
  4867. int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  4868. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  4869. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  4870. L"%11i(0x%08x), expected = %11i(0x%08x)",
  4871. i, p->input1, p->input1, p->input2, p->input2,
  4872. p->input3, p->input3, p->output, p->output, val1,
  4873. val1);
  4874. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  4875. }
  4876. }
  4877. TEST_F(ExecutionTest, BinaryUintOpTest) {
  4878. WEX::TestExecution::SetVerifyOutput verifySettings(
  4879. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4880. CComPtr<IStream> pStream;
  4881. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4882. CComPtr<ID3D12Device> pDevice;
  4883. if (!CreateDevice(&pDevice)) {
  4884. return;
  4885. }
  4886. // Read data from the table
  4887. size_t tableSize = sizeof(BinaryUintOpParameters) / sizeof(TableParameter);
  4888. TableParameterHandler handler(BinaryUintOpParameters, tableSize);
  4889. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4890. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4891. std::vector<unsigned int> *Validation_Input1 =
  4892. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4893. std::vector<unsigned int> *Validation_Input2 =
  4894. &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  4895. std::vector<unsigned int> *Validation_Expected1 =
  4896. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4897. std::vector<unsigned int> *Validation_Expected2 =
  4898. &handler.GetTableParamByName(L"Validation.Expected2")->m_uint32Table;
  4899. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4900. size_t count = Validation_Input1->size();
  4901. int numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  4902. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4903. pDevice, m_support, pStream, "BinaryUintOp",
  4904. // this callbacked is called when the test
  4905. // is creating the resource to run the test
  4906. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4907. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  4908. size_t size = sizeof(SBinaryUintOp) * count;
  4909. Data.resize(size);
  4910. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)Data.data();
  4911. for (size_t i = 0; i < count; ++i) {
  4912. SBinaryUintOp *p = &pPrimitives[i];
  4913. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4914. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4915. p->input1 = val1;
  4916. p->input2 = val2;
  4917. }
  4918. // use shader from data table
  4919. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  4920. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  4921. });
  4922. MappedData data;
  4923. test->Test->GetReadBackData("SBinaryUintOp", &data);
  4924. SBinaryUintOp *pPrimitives = (SBinaryUintOp *)data.data();
  4925. WEX::TestExecution::DisableVerifyExceptions dve;
  4926. if (numExpected == 2) {
  4927. for (unsigned i = 0; i < count; ++i) {
  4928. SBinaryUintOp *p = &pPrimitives[i];
  4929. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4930. unsigned int val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  4931. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  4932. L"%11u(0x%08x), output1 = "
  4933. L"%11u(0x%08x), expected1 = %11u(0x%08x), output2 = "
  4934. L"%11u(0x%08x), expected2 = %11u(0x%08x)",
  4935. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  4936. p->output1, val1, val1, p->output2, p->output2, val2,
  4937. val2);
  4938. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4939. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  4940. }
  4941. }
  4942. else if (numExpected == 1) {
  4943. for (unsigned i = 0; i < count; ++i) {
  4944. SBinaryUintOp *p = &pPrimitives[i];
  4945. unsigned int val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  4946. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  4947. L"%11u(0x%08x), output = "
  4948. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  4949. p->input1, p->input1, p->input2, p->input2,
  4950. p->output1, p->output1, val1, val1);
  4951. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  4952. }
  4953. }
  4954. else {
  4955. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  4956. }
  4957. }
  4958. TEST_F(ExecutionTest, TertiaryUintOpTest) {
  4959. WEX::TestExecution::SetVerifyOutput verifySettings(
  4960. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  4961. CComPtr<IStream> pStream;
  4962. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  4963. CComPtr<ID3D12Device> pDevice;
  4964. if (!CreateDevice(&pDevice)) {
  4965. return;
  4966. }
  4967. // Read data from the table
  4968. size_t tableSize = sizeof(TertiaryUintOpParameters) / sizeof(TableParameter);
  4969. TableParameterHandler handler(TertiaryUintOpParameters, tableSize);
  4970. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  4971. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  4972. std::vector<unsigned int> *Validation_Input1 =
  4973. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  4974. std::vector<unsigned int> *Validation_Input2 =
  4975. &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  4976. std::vector<unsigned int> *Validation_Input3 =
  4977. &handler.GetTableParamByName(L"Validation.Input3")->m_uint32Table;
  4978. std::vector<unsigned int> *Validation_Expected =
  4979. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  4980. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  4981. size_t count = Validation_Input1->size();
  4982. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  4983. pDevice, m_support, pStream, "TertiaryUintOp",
  4984. // this callbacked is called when the test
  4985. // is creating the resource to run the test
  4986. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  4987. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  4988. size_t size = sizeof(STertiaryUintOp) * count;
  4989. Data.resize(size);
  4990. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)Data.data();
  4991. for (size_t i = 0; i < count; ++i) {
  4992. STertiaryUintOp *p = &pPrimitives[i];
  4993. unsigned int val1 = (*Validation_Input1)[i % Validation_Input1->size()];
  4994. unsigned int val2 = (*Validation_Input2)[i % Validation_Input2->size()];
  4995. unsigned int val3 = (*Validation_Input3)[i % Validation_Input3->size()];
  4996. p->input1 = val1;
  4997. p->input2 = val2;
  4998. p->input3 = val3;
  4999. }
  5000. // use shader from data table
  5001. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5002. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5003. });
  5004. MappedData data;
  5005. test->Test->GetReadBackData("STertiaryUintOp", &data);
  5006. STertiaryUintOp *pPrimitives = (STertiaryUintOp *)data.data();
  5007. WEX::TestExecution::DisableVerifyExceptions dve;
  5008. for (unsigned i = 0; i < count; ++i) {
  5009. STertiaryUintOp *p = &pPrimitives[i];
  5010. unsigned int val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  5011. LogCommentFmt(L"element #%u, input1 = %11u(0x%08x), input2 = "
  5012. L"%11u(0x%08x), input3 = %11u(0x%08x), output = "
  5013. L"%11u(0x%08x), expected = %11u(0x%08x)", i,
  5014. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  5015. p->output, p->output, val1, val1);
  5016. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  5017. }
  5018. }
  5019. // 16 bit integer type tests
  5020. TEST_F(ExecutionTest, UnaryInt16OpTest) {
  5021. WEX::TestExecution::SetVerifyOutput verifySettings(
  5022. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5023. CComPtr<IStream> pStream;
  5024. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5025. CComPtr<ID3D12Device> pDevice;
  5026. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5027. return;
  5028. }
  5029. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5030. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5031. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5032. return;
  5033. }
  5034. // Read data from the table
  5035. int tableSize = sizeof(UnaryInt16OpParameters) / sizeof(TableParameter);
  5036. TableParameterHandler handler(UnaryInt16OpParameters, tableSize);
  5037. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5038. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5039. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5040. std::vector<short> *Validation_Input =
  5041. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  5042. std::vector<short> *Validation_Expected =
  5043. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  5044. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5045. size_t count = Validation_Input->size();
  5046. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5047. pDevice, m_support, pStream, "UnaryIntOp",
  5048. // this callbacked is called when the test
  5049. // is creating the resource to run the test
  5050. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5051. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryIntOp"));
  5052. size_t size = sizeof(SUnaryInt16Op) * count;
  5053. Data.resize(size);
  5054. SUnaryInt16Op *pPrimitives = (SUnaryInt16Op *)Data.data();
  5055. for (size_t i = 0; i < count; ++i) {
  5056. SUnaryInt16Op *p = &pPrimitives[i];
  5057. p->input = (*Validation_Input)[i % Validation_Input->size()];
  5058. }
  5059. // use shader data table
  5060. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5061. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5062. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5063. });
  5064. MappedData data;
  5065. test->Test->GetReadBackData("SUnaryIntOp", &data);
  5066. SUnaryInt16Op *pPrimitives = (SUnaryInt16Op *)data.data();
  5067. WEX::TestExecution::DisableVerifyExceptions dve;
  5068. for (unsigned i = 0; i < count; ++i) {
  5069. SUnaryInt16Op *p = &pPrimitives[i];
  5070. short val = (*Validation_Expected)[i % Validation_Expected->size()];
  5071. LogCommentFmt(L"element #%u, input = %5hi(0x%08x), output = %5hi(0x%08x), "
  5072. L"expected = %5hi(0x%08x)",
  5073. i, p->input, p->input, p->output, p->output, val, val);
  5074. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  5075. }
  5076. }
  5077. TEST_F(ExecutionTest, UnaryUint16OpTest) {
  5078. WEX::TestExecution::SetVerifyOutput verifySettings(
  5079. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5080. CComPtr<IStream> pStream;
  5081. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5082. CComPtr<ID3D12Device> pDevice;
  5083. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5084. return;
  5085. }
  5086. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5087. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5088. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5089. return;
  5090. }
  5091. // Read data from the table
  5092. int tableSize = sizeof(UnaryUint16OpParameters) / sizeof(TableParameter);
  5093. TableParameterHandler handler(UnaryUint16OpParameters, tableSize);
  5094. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5095. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5096. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5097. std::vector<unsigned short> *Validation_Input =
  5098. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5099. std::vector<unsigned short> *Validation_Expected =
  5100. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5101. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5102. size_t count = Validation_Input->size();
  5103. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5104. pDevice, m_support, pStream, "UnaryUintOp",
  5105. // this callbacked is called when the test
  5106. // is creating the resource to run the test
  5107. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5108. VERIFY_IS_TRUE(0 == _stricmp(Name, "SUnaryUintOp"));
  5109. size_t size = sizeof(SUnaryUint16Op) * count;
  5110. Data.resize(size);
  5111. SUnaryUint16Op *pPrimitives = (SUnaryUint16Op *)Data.data();
  5112. for (size_t i = 0; i < count; ++i) {
  5113. SUnaryUint16Op *p = &pPrimitives[i];
  5114. p->input = (*Validation_Input)[i % Validation_Input->size()];
  5115. }
  5116. // use shader data table
  5117. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5118. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5119. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5120. });
  5121. MappedData data;
  5122. test->Test->GetReadBackData("SUnaryUintOp", &data);
  5123. SUnaryUint16Op *pPrimitives = (SUnaryUint16Op *)data.data();
  5124. WEX::TestExecution::DisableVerifyExceptions dve;
  5125. for (unsigned i = 0; i < count; ++i) {
  5126. SUnaryUint16Op *p = &pPrimitives[i];
  5127. unsigned short val = (*Validation_Expected)[i % Validation_Expected->size()];
  5128. LogCommentFmt(L"element #%u, input = %5hu(0x%08x), output = %5hu(0x%08x), "
  5129. L"expected = %5hu(0x%08x)",
  5130. i, p->input, p->input, p->output, p->output, val, val);
  5131. VerifyOutputWithExpectedValueInt(p->output, val, Validation_Tolerance);
  5132. }
  5133. }
  5134. TEST_F(ExecutionTest, BinaryInt16OpTest) {
  5135. WEX::TestExecution::SetVerifyOutput verifySettings(
  5136. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5137. CComPtr<IStream> pStream;
  5138. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5139. CComPtr<ID3D12Device> pDevice;
  5140. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5141. return;
  5142. }
  5143. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5144. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5145. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5146. return;
  5147. }
  5148. // Read data from the table
  5149. size_t tableSize = sizeof(BinaryInt16OpParameters) / sizeof(TableParameter);
  5150. TableParameterHandler handler(BinaryInt16OpParameters, tableSize);
  5151. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5152. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5153. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5154. std::vector<short> *Validation_Input1 =
  5155. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  5156. std::vector<short> *Validation_Input2 =
  5157. &handler.GetTableParamByName(L"Validation.Input2")->m_int16Table;
  5158. std::vector<short> *Validation_Expected1 =
  5159. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  5160. std::vector<short> *Validation_Expected2 =
  5161. &handler.GetTableParamByName(L"Validation.Expected2")->m_int16Table;
  5162. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5163. size_t count = Validation_Input1->size();
  5164. size_t numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  5165. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5166. pDevice, m_support, pStream, "BinaryIntOp",
  5167. // this callbacked is called when the test
  5168. // is creating the resource to run the test
  5169. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5170. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryIntOp"));
  5171. size_t size = sizeof(SBinaryInt16Op) * count;
  5172. Data.resize(size);
  5173. SBinaryInt16Op *pPrimitives = (SBinaryInt16Op *)Data.data();
  5174. for (size_t i = 0; i < count; ++i) {
  5175. SBinaryInt16Op *p = &pPrimitives[i];
  5176. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5177. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5178. }
  5179. // use shader from data table
  5180. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5181. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5182. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5183. });
  5184. MappedData data;
  5185. test->Test->GetReadBackData("SBinaryIntOp", &data);
  5186. SBinaryInt16Op *pPrimitives = (SBinaryInt16Op *)data.data();
  5187. WEX::TestExecution::DisableVerifyExceptions dve;
  5188. if (numExpected == 2) {
  5189. for (unsigned i = 0; i < count; ++i) {
  5190. SBinaryInt16Op *p = &pPrimitives[i];
  5191. short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5192. short val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5193. LogCommentFmt(L"element #%u, input1 = %5hi(0x%08x), input2 = "
  5194. L"%5hi(0x%08x), output1 = "
  5195. L"%5hi(0x%08x), expected1 = %5hi(0x%08x), output2 = "
  5196. L"%5hi(0x%08x), expected2 = %5hi(0x%08x)",
  5197. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  5198. p->output1, val1, val1, p->output2, p->output2, val2,
  5199. val2);
  5200. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5201. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  5202. }
  5203. }
  5204. else if (numExpected == 1) {
  5205. for (unsigned i = 0; i < count; ++i) {
  5206. SBinaryInt16Op *p = &pPrimitives[i];
  5207. short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5208. LogCommentFmt(L"element #%u, input1 = %5hi(0x%08x), input2 = "
  5209. L"%5hi(0x%08x), output = "
  5210. L"%5hi(0x%08x), expected = %5hi(0x%08x)", i,
  5211. p->input1, p->input1, p->input2, p->input2,
  5212. p->output1, p->output1, val1, val1);
  5213. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5214. }
  5215. }
  5216. else {
  5217. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  5218. }
  5219. }
  5220. TEST_F(ExecutionTest, TertiaryInt16OpTest) {
  5221. WEX::TestExecution::SetVerifyOutput verifySettings(
  5222. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5223. CComPtr<IStream> pStream;
  5224. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5225. CComPtr<ID3D12Device> pDevice;
  5226. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5227. return;
  5228. }
  5229. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5230. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5231. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5232. return;
  5233. }
  5234. // Read data from the table
  5235. size_t tableSize = sizeof(TertiaryInt16OpParameters) / sizeof(TableParameter);
  5236. TableParameterHandler handler(TertiaryInt16OpParameters, tableSize);
  5237. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5238. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5239. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5240. std::vector<short> *Validation_Input1 =
  5241. &handler.GetTableParamByName(L"Validation.Input1")->m_int16Table;
  5242. std::vector<short> *Validation_Input2 =
  5243. &handler.GetTableParamByName(L"Validation.Input2")->m_int16Table;
  5244. std::vector<short> *Validation_Input3 =
  5245. &handler.GetTableParamByName(L"Validation.Input3")->m_int16Table;
  5246. std::vector<short> *Validation_Expected =
  5247. &handler.GetTableParamByName(L"Validation.Expected1")->m_int16Table;
  5248. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5249. size_t count = Validation_Input1->size();
  5250. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5251. pDevice, m_support, pStream, "TertiaryIntOp",
  5252. // this callbacked is called when the test
  5253. // is creating the resource to run the test
  5254. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5255. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryIntOp"));
  5256. size_t size = sizeof(STertiaryInt16Op) * count;
  5257. Data.resize(size);
  5258. STertiaryInt16Op *pPrimitives = (STertiaryInt16Op *)Data.data();
  5259. for (size_t i = 0; i < count; ++i) {
  5260. STertiaryInt16Op *p = &pPrimitives[i];
  5261. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5262. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5263. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5264. }
  5265. // use shader from data table
  5266. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5267. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5268. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5269. });
  5270. MappedData data;
  5271. test->Test->GetReadBackData("STertiaryIntOp", &data);
  5272. STertiaryInt16Op *pPrimitives = (STertiaryInt16Op *)data.data();
  5273. WEX::TestExecution::DisableVerifyExceptions dve;
  5274. for (unsigned i = 0; i < count; ++i) {
  5275. STertiaryInt16Op *p = &pPrimitives[i];
  5276. short val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  5277. LogCommentFmt(L"element #%u, input1 = %11i(0x%08x), input2 = "
  5278. L"%11i(0x%08x), input3= %11i(0x%08x), output = "
  5279. L"%11i(0x%08x), expected = %11i(0x%08x)",
  5280. i, p->input1, p->input1, p->input2, p->input2,
  5281. p->input3, p->input3, p->output, p->output, val1,
  5282. val1);
  5283. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  5284. }
  5285. }
  5286. TEST_F(ExecutionTest, BinaryUint16OpTest) {
  5287. WEX::TestExecution::SetVerifyOutput verifySettings(
  5288. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5289. CComPtr<IStream> pStream;
  5290. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5291. CComPtr<ID3D12Device> pDevice;
  5292. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5293. return;
  5294. }
  5295. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5296. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5297. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5298. return;
  5299. }
  5300. // Read data from the table
  5301. size_t tableSize = sizeof(BinaryUint16OpParameters) / sizeof(TableParameter);
  5302. TableParameterHandler handler(BinaryUint16OpParameters, tableSize);
  5303. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5304. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5305. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5306. std::vector<unsigned short> *Validation_Input1 =
  5307. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5308. std::vector<unsigned short> *Validation_Input2 =
  5309. &handler.GetTableParamByName(L"Validation.Input2")->m_uint16Table;
  5310. std::vector<unsigned short> *Validation_Expected1 =
  5311. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5312. std::vector<unsigned short> *Validation_Expected2 =
  5313. &handler.GetTableParamByName(L"Validation.Expected2")->m_uint16Table;
  5314. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5315. size_t count = Validation_Input1->size();
  5316. int numExpected = Validation_Expected2->size() == 0 ? 1 : 2;
  5317. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5318. pDevice, m_support, pStream, "BinaryUintOp",
  5319. // this callbacked is called when the test
  5320. // is creating the resource to run the test
  5321. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5322. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryUintOp"));
  5323. size_t size = sizeof(SBinaryUint16Op) * count;
  5324. Data.resize(size);
  5325. SBinaryUint16Op *pPrimitives = (SBinaryUint16Op *)Data.data();
  5326. for (size_t i = 0; i < count; ++i) {
  5327. SBinaryUint16Op *p = &pPrimitives[i];
  5328. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5329. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5330. }
  5331. // use shader from data table
  5332. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5333. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5334. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5335. });
  5336. MappedData data;
  5337. test->Test->GetReadBackData("SBinaryUintOp", &data);
  5338. SBinaryUint16Op *pPrimitives = (SBinaryUint16Op *)data.data();
  5339. WEX::TestExecution::DisableVerifyExceptions dve;
  5340. if (numExpected == 2) {
  5341. for (unsigned i = 0; i < count; ++i) {
  5342. SBinaryUint16Op *p = &pPrimitives[i];
  5343. unsigned short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5344. unsigned short val2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5345. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5346. L"%5hu(0x%08x), output1 = "
  5347. L"%5hu(0x%08x), expected1 = %5hu(0x%08x), output2 = "
  5348. L"%5hu(0x%08x), expected2 = %5hu(0x%08x)",
  5349. i, p->input1, p->input1, p->input2, p->input2, p->output1,
  5350. p->output1, val1, val1, p->output2, p->output2, val2,
  5351. val2);
  5352. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5353. VerifyOutputWithExpectedValueInt(p->output2, val2, Validation_Tolerance);
  5354. }
  5355. }
  5356. else if (numExpected == 1) {
  5357. for (unsigned i = 0; i < count; ++i) {
  5358. SBinaryUint16Op *p = &pPrimitives[i];
  5359. unsigned short val1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5360. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5361. L"%5hu(0x%08x), output = "
  5362. L"%5hu(0x%08x), expected = %5hu(0x%08x)", i,
  5363. p->input1, p->input1, p->input2, p->input2,
  5364. p->output1, p->output1, val1, val1);
  5365. VerifyOutputWithExpectedValueInt(p->output1, val1, Validation_Tolerance);
  5366. }
  5367. }
  5368. else {
  5369. LogErrorFmt(L"Unexpected number of expected values for operation %i", numExpected);
  5370. }
  5371. }
  5372. TEST_F(ExecutionTest, TertiaryUint16OpTest) {
  5373. WEX::TestExecution::SetVerifyOutput verifySettings(
  5374. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5375. CComPtr<IStream> pStream;
  5376. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5377. CComPtr<ID3D12Device> pDevice;
  5378. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5379. return;
  5380. }
  5381. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5382. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5383. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5384. return;
  5385. }
  5386. // Read data from the table
  5387. size_t tableSize = sizeof(TertiaryUint16OpParameters) / sizeof(TableParameter);
  5388. TableParameterHandler handler(TertiaryUint16OpParameters, tableSize);
  5389. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5390. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5391. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5392. std::vector<unsigned short> *Validation_Input1 =
  5393. &handler.GetTableParamByName(L"Validation.Input1")->m_uint16Table;
  5394. std::vector<unsigned short> *Validation_Input2 =
  5395. &handler.GetTableParamByName(L"Validation.Input2")->m_uint16Table;
  5396. std::vector<unsigned short> *Validation_Input3 =
  5397. &handler.GetTableParamByName(L"Validation.Input3")->m_uint16Table;
  5398. std::vector<unsigned short> *Validation_Expected =
  5399. &handler.GetTableParamByName(L"Validation.Expected1")->m_uint16Table;
  5400. int Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_int32;
  5401. size_t count = Validation_Input1->size();
  5402. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5403. pDevice, m_support, pStream, "TertiaryUintOp",
  5404. // this callbacked is called when the test
  5405. // is creating the resource to run the test
  5406. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5407. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryUintOp"));
  5408. size_t size = sizeof(STertiaryUint16Op) * count;
  5409. Data.resize(size);
  5410. STertiaryUint16Op *pPrimitives = (STertiaryUint16Op *)Data.data();
  5411. for (size_t i = 0; i < count; ++i) {
  5412. STertiaryUint16Op *p = &pPrimitives[i];
  5413. p->input1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5414. p->input2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5415. p->input3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5416. }
  5417. // use shader from data table
  5418. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5419. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5420. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5421. });
  5422. MappedData data;
  5423. test->Test->GetReadBackData("STertiaryUintOp", &data);
  5424. STertiaryUint16Op *pPrimitives = (STertiaryUint16Op *)data.data();
  5425. WEX::TestExecution::DisableVerifyExceptions dve;
  5426. for (unsigned i = 0; i < count; ++i) {
  5427. STertiaryUint16Op *p = &pPrimitives[i];
  5428. unsigned short val1 = (*Validation_Expected)[i % Validation_Expected->size()];
  5429. LogCommentFmt(L"element #%u, input1 = %5hu(0x%08x), input2 = "
  5430. L"%5hu(0x%08x), input3 = %5hu(0x%08x), output = "
  5431. L"%5hu(0x%08x), expected = %5hu(0x%08x)", i,
  5432. p->input1, p->input1, p->input2, p->input2, p->input3, p->input3,
  5433. p->output, p->output, val1, val1);
  5434. VerifyOutputWithExpectedValueInt(p->output, val1, Validation_Tolerance);
  5435. }
  5436. }
  5437. TEST_F(ExecutionTest, DotTest) {
  5438. WEX::TestExecution::SetVerifyOutput verifySettings(
  5439. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5440. CComPtr<IStream> pStream;
  5441. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5442. CComPtr<ID3D12Device> pDevice;
  5443. if (!CreateDevice(&pDevice)) {
  5444. return;
  5445. }
  5446. int tableSize = sizeof(DotOpParameters) / sizeof(TableParameter);
  5447. TableParameterHandler handler(DotOpParameters, tableSize);
  5448. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5449. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5450. std::vector<WEX::Common::String> *Validation_Input1 =
  5451. &handler.GetTableParamByName(L"Validation.Input1")->m_StringTable;
  5452. std::vector<WEX::Common::String> *Validation_Input2 =
  5453. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5454. std::vector<WEX::Common::String> *Validation_dot2 =
  5455. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  5456. std::vector<WEX::Common::String> *Validation_dot3 =
  5457. &handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable;
  5458. std::vector<WEX::Common::String> *Validation_dot4 =
  5459. &handler.GetTableParamByName(L"Validation.Expected3")->m_StringTable;
  5460. PCWSTR Validation_type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5461. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5462. size_t count = Validation_Input1->size();
  5463. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5464. pDevice, m_support, pStream, "DotOp",
  5465. // this callbacked is called when the test
  5466. // is creating the resource to run the test
  5467. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5468. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDotOp"));
  5469. size_t size = sizeof(SDotOp) * count;
  5470. Data.resize(size);
  5471. SDotOp *pPrimitives = (SDotOp*)Data.data();
  5472. for (size_t i = 0; i < count; ++i) {
  5473. SDotOp *p = &pPrimitives[i];
  5474. XMFLOAT4 val1,val2;
  5475. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input1)[i],
  5476. (float *)&val1, 4));
  5477. VERIFY_SUCCEEDED(ParseDataToVectorFloat((*Validation_Input2)[i],
  5478. (float *)&val2, 4));
  5479. p->input1 = val1;
  5480. p->input2 = val2;
  5481. }
  5482. // use shader from data table
  5483. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5484. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5485. });
  5486. MappedData data;
  5487. test->Test->GetReadBackData("SDotOp", &data);
  5488. SDotOp *pPrimitives = (SDotOp*)data.data();
  5489. WEX::TestExecution::DisableVerifyExceptions dve;
  5490. for (size_t i = 0; i < count; ++i) {
  5491. SDotOp *p = &pPrimitives[i];
  5492. float dot2, dot3, dot4;
  5493. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot2)[i], dot2));
  5494. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot3)[i], dot3));
  5495. VERIFY_SUCCEEDED(ParseDataToFloat((*Validation_dot4)[i], dot4));
  5496. LogCommentFmt(
  5497. L"element #%u, input1 = (%f, %f, %f, %f), input2 = (%f, %f, "
  5498. L"%f, %f), \n dot2 = %f, dot2_expected = %f, dot3 = %f, "
  5499. L"dot3_expected = %f, dot4 = %f, dot4_expected = %f",
  5500. i, p->input1.x, p->input1.y, p->input1.z, p->input1.w, p->input2.x,
  5501. p->input2.y, p->input2.z, p->input2.w, p->o_dot2, dot2, p->o_dot3, dot3,
  5502. p->o_dot4, dot4);
  5503. VerifyOutputWithExpectedValueFloat(p->o_dot2, dot2, Validation_type,
  5504. tolerance);
  5505. VerifyOutputWithExpectedValueFloat(p->o_dot3, dot3, Validation_type,
  5506. tolerance);
  5507. VerifyOutputWithExpectedValueFloat(p->o_dot4, dot4, Validation_type,
  5508. tolerance);
  5509. }
  5510. }
  5511. TEST_F(ExecutionTest, Dot2AddHalfTest) {
  5512. WEX::TestExecution::SetVerifyOutput verifySettings(
  5513. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5514. CComPtr<IStream> pStream;
  5515. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5516. CComPtr<ID3D12Device> pDevice;
  5517. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5518. return;
  5519. }
  5520. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  5521. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  5522. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  5523. return;
  5524. }
  5525. int tableSize = sizeof(Dot2AddHalfOpParameters) / sizeof(TableParameter);
  5526. TableParameterHandler handler(Dot2AddHalfOpParameters, tableSize);
  5527. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5528. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5529. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5530. std::vector<WEX::Common::String> *validation_input1 =
  5531. &handler.GetTableParamByName(L"Validation.Input1")->m_StringTable;
  5532. std::vector<WEX::Common::String> *validation_input2 =
  5533. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5534. std::vector<float> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_floatTable;
  5535. std::vector<float> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_floatTable;
  5536. PCWSTR Validation_type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5537. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5538. size_t count = validation_input1->size();
  5539. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5540. pDevice, m_support, pStream, "Dot2AddHalfOp",
  5541. // this callback is called when the test
  5542. // is creating the resource to run the test
  5543. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5544. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot2AddHalfOp"));
  5545. size_t size = sizeof(SDot2AddHalfOp) * count;
  5546. Data.resize(size);
  5547. SDot2AddHalfOp *pPrimitives = (SDot2AddHalfOp*)Data.data();
  5548. for (size_t i = 0; i < count; ++i) {
  5549. SDot2AddHalfOp *p = &pPrimitives[i];
  5550. Half2 val1,val2;
  5551. VERIFY_SUCCEEDED(ParseDataToVectorHalf((*validation_input1)[i],
  5552. (uint16_t *)&val1, 2));
  5553. VERIFY_SUCCEEDED(ParseDataToVectorHalf((*validation_input2)[i],
  5554. (uint16_t *)&val2, 2));
  5555. p->input1 = val1;
  5556. p->input2 = val2;
  5557. p->acc = (*validation_acc)[i];
  5558. }
  5559. // use shader from data table
  5560. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5561. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5562. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5563. });
  5564. MappedData data;
  5565. test->Test->GetReadBackData("SDot2AddHalfOp", &data);
  5566. SDot2AddHalfOp *pPrimitives = (SDot2AddHalfOp*)data.data();
  5567. WEX::TestExecution::DisableVerifyExceptions dve;
  5568. for (size_t i = 0; i < count; ++i) {
  5569. SDot2AddHalfOp *p = &pPrimitives[i];
  5570. float expectedResult = (*validation_result)[i];
  5571. float input1x = ConvertFloat16ToFloat32(p->input1.x);
  5572. float input1y = ConvertFloat16ToFloat32(p->input1.y);
  5573. float input2x = ConvertFloat16ToFloat32(p->input2.x);
  5574. float input2y = ConvertFloat16ToFloat32(p->input2.y);
  5575. LogCommentFmt(
  5576. L"element #%u, input1 = (%f, %f), input2 = (%f, %f), acc = %f\n"
  5577. L"result = %f, result_expected = %f",
  5578. i, input1x, input1y, input2x, input2y, p->acc, p->result, expectedResult);
  5579. VerifyOutputWithExpectedValueFloat(p->result, expectedResult, Validation_type, tolerance);
  5580. }
  5581. }
  5582. TEST_F(ExecutionTest, Dot4AddI8PackedTest) {
  5583. WEX::TestExecution::SetVerifyOutput verifySettings(
  5584. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5585. CComPtr<IStream> pStream;
  5586. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5587. CComPtr<ID3D12Device> pDevice;
  5588. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5589. return;
  5590. }
  5591. int tableSize = sizeof(Dot4AddI8PackedOpParameters) / sizeof(TableParameter);
  5592. TableParameterHandler handler(Dot4AddI8PackedOpParameters, tableSize);
  5593. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5594. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5595. std::vector<uint32_t> *validation_input1 = &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5596. std::vector<uint32_t> *validation_input2 = &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  5597. std::vector<int32_t> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_int32Table;
  5598. std::vector<int32_t> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_int32Table;
  5599. size_t count = validation_input1->size();
  5600. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5601. pDevice, m_support, pStream, "Dot4AddI8PackedOp",
  5602. // this callback is called when the test
  5603. // is creating the resource to run the test
  5604. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5605. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot4AddI8PackedOp"));
  5606. size_t size = sizeof(SDot4AddI8PackedOp) * count;
  5607. Data.resize(size);
  5608. SDot4AddI8PackedOp *pPrimitives = (SDot4AddI8PackedOp*)Data.data();
  5609. for (size_t i = 0; i < count; ++i) {
  5610. SDot4AddI8PackedOp *p = &pPrimitives[i];
  5611. p->input1 = (*validation_input1)[i];
  5612. p->input2 = (*validation_input2)[i];
  5613. p->acc = (*validation_acc)[i];
  5614. }
  5615. // use shader from data table
  5616. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5617. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5618. });
  5619. MappedData data;
  5620. test->Test->GetReadBackData("SDot4AddI8PackedOp", &data);
  5621. SDot4AddI8PackedOp *pPrimitives = (SDot4AddI8PackedOp*)data.data();
  5622. WEX::TestExecution::DisableVerifyExceptions dve;
  5623. for (size_t i = 0; i < count; ++i) {
  5624. SDot4AddI8PackedOp *p = &pPrimitives[i];
  5625. int32_t expectedResult = (*validation_result)[i];
  5626. LogCommentFmt(
  5627. L"element #%u, input1 = %u, input2 = %u, acc = %d \n"
  5628. L"result = %d, result_expected = %d",
  5629. i, p->input1, p->input2, p->acc, p->result, expectedResult);
  5630. VerifyOutputWithExpectedValueInt(p->result, expectedResult, 0);
  5631. }
  5632. }
  5633. TEST_F(ExecutionTest, Dot4AddU8PackedTest) {
  5634. WEX::TestExecution::SetVerifyOutput verifySettings(
  5635. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5636. CComPtr<IStream> pStream;
  5637. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5638. CComPtr<ID3D12Device> pDevice;
  5639. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_4, false)) {
  5640. return;
  5641. }
  5642. int tableSize = sizeof(Dot4AddU8PackedOpParameters) / sizeof(TableParameter);
  5643. TableParameterHandler handler(Dot4AddU8PackedOpParameters, tableSize);
  5644. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5645. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5646. std::vector<uint32_t> *validation_input1 = &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5647. std::vector<uint32_t> *validation_input2 = &handler.GetTableParamByName(L"Validation.Input2")->m_uint32Table;
  5648. std::vector<uint32_t> *validation_acc = &handler.GetTableParamByName(L"Validation.Input3")->m_uint32Table;
  5649. std::vector<uint32_t> *validation_result = &handler.GetTableParamByName(L"Validation.Expected1")->m_uint32Table;
  5650. size_t count = validation_input1->size();
  5651. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5652. pDevice, m_support, pStream, "Dot4AddU8PackedOp",
  5653. // this callback is called when the test
  5654. // is creating the resource to run the test
  5655. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5656. VERIFY_IS_TRUE(0 == _stricmp(Name, "SDot4AddU8PackedOp"));
  5657. size_t size = sizeof(SDot4AddU8PackedOp) * count;
  5658. Data.resize(size);
  5659. SDot4AddU8PackedOp *pPrimitives = (SDot4AddU8PackedOp*)Data.data();
  5660. for (size_t i = 0; i < count; ++i) {
  5661. SDot4AddU8PackedOp *p = &pPrimitives[i];
  5662. p->input1 = (*validation_input1)[i];
  5663. p->input2 = (*validation_input2)[i];
  5664. p->acc = (*validation_acc)[i];
  5665. }
  5666. // use shader from data table
  5667. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5668. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5669. });
  5670. MappedData data;
  5671. test->Test->GetReadBackData("SDot4AddU8PackedOp", &data);
  5672. SDot4AddU8PackedOp *pPrimitives = (SDot4AddU8PackedOp*)data.data();
  5673. WEX::TestExecution::DisableVerifyExceptions dve;
  5674. for (size_t i = 0; i < count; ++i) {
  5675. SDot4AddU8PackedOp *p = &pPrimitives[i];
  5676. uint32_t expectedResult = (*validation_result)[i];
  5677. LogCommentFmt(
  5678. L"element #%u, input1 = %u, input2 = %u, acc = %u \n"
  5679. L"result = %u, result_expected = %u, ",
  5680. i, p->input1, p->input2, p->acc, p->result, expectedResult);
  5681. VerifyOutputWithExpectedValueUInt(p->result, expectedResult, 0);
  5682. }
  5683. }
  5684. TEST_F(ExecutionTest, Msad4Test) {
  5685. WEX::TestExecution::SetVerifyOutput verifySettings(
  5686. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5687. CComPtr<IStream> pStream;
  5688. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5689. CComPtr<ID3D12Device> pDevice;
  5690. if (!CreateDevice(&pDevice)) {
  5691. return;
  5692. }
  5693. size_t tableSize = sizeof(Msad4OpParameters) / sizeof(TableParameter);
  5694. TableParameterHandler handler(Msad4OpParameters, tableSize);
  5695. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5696. double tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5697. std::vector<unsigned int> *Validation_Reference =
  5698. &handler.GetTableParamByName(L"Validation.Input1")->m_uint32Table;
  5699. std::vector<WEX::Common::String> *Validation_Source =
  5700. &handler.GetTableParamByName(L"Validation.Input2")->m_StringTable;
  5701. std::vector<WEX::Common::String> *Validation_Accum =
  5702. &handler.GetTableParamByName(L"Validation.Input3")->m_StringTable;
  5703. std::vector<WEX::Common::String> *Validation_Expected =
  5704. &handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable;
  5705. size_t count = Validation_Expected->size();
  5706. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5707. pDevice, m_support, pStream, "Msad4",
  5708. // this callbacked is called when the test
  5709. // is creating the resource to run the test
  5710. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5711. VERIFY_IS_TRUE(0 == _stricmp(Name, "SMsad4"));
  5712. size_t size = sizeof(SMsad4) * count;
  5713. Data.resize(size);
  5714. SMsad4 *pPrimitives = (SMsad4*)Data.data();
  5715. for (size_t i = 0; i < count; ++i) {
  5716. SMsad4 *p = &pPrimitives[i];
  5717. XMUINT2 src;
  5718. XMUINT4 accum;
  5719. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Source)[i], (unsigned int*)&src, 2));
  5720. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Accum)[i], (unsigned int*)&accum, 4));
  5721. p->ref = (*Validation_Reference)[i];
  5722. p->src = src;
  5723. p->accum = accum;
  5724. }
  5725. // use shader from data table
  5726. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5727. });
  5728. MappedData data;
  5729. test->Test->GetReadBackData("SMsad4", &data);
  5730. SMsad4 *pPrimitives = (SMsad4*)data.data();
  5731. WEX::TestExecution::DisableVerifyExceptions dve;
  5732. for (size_t i = 0; i < count; ++i) {
  5733. SMsad4 *p = &pPrimitives[i];
  5734. XMUINT4 result;
  5735. VERIFY_SUCCEEDED(ParseDataToVectorUint((*Validation_Expected)[i],
  5736. (unsigned int *)&result, 4));
  5737. LogCommentFmt(
  5738. L"element #%u, ref = %u(0x%08x), src = %u(0x%08x), %u(0x%08x), "
  5739. L"accum = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  5740. L"result = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x),\n"
  5741. L"expected = %u(0x%08x), %u(0x%08x), %u(0x%08x), %u(0x%08x)", i,
  5742. p->ref, p->ref, p->src.x, p->src.x, p->src.y, p->src.y, p->accum.x,
  5743. p->accum.x, p->accum.y, p->accum.y, p->accum.z, p->accum.z,
  5744. p->accum.w, p->accum.w, p->result.x, p->result.x, p->result.y,
  5745. p->result.y, p->result.z, p->result.z, p->result.w, p->result.w,
  5746. result.x, result.x, result.y, result.y, result.z, result.z,
  5747. result.w, result.w);
  5748. int toleranceInt = (int)tolerance;
  5749. VerifyOutputWithExpectedValueInt(p->result.x, result.x, toleranceInt);
  5750. VerifyOutputWithExpectedValueInt(p->result.y, result.y, toleranceInt);
  5751. VerifyOutputWithExpectedValueInt(p->result.z, result.z, toleranceInt);
  5752. VerifyOutputWithExpectedValueInt(p->result.w, result.w, toleranceInt);
  5753. }
  5754. }
  5755. TEST_F(ExecutionTest, DenormBinaryFloatOpTest) {
  5756. WEX::TestExecution::SetVerifyOutput verifySettings(
  5757. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5758. CComPtr<IStream> pStream;
  5759. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5760. CComPtr<ID3D12Device> pDevice;
  5761. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5762. return;
  5763. }
  5764. // Read data from the table
  5765. int tableSize = sizeof(DenormBinaryFPOpParameters) / sizeof(TableParameter);
  5766. TableParameterHandler handler(DenormBinaryFPOpParameters, tableSize);
  5767. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5768. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5769. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5770. std::vector<WEX::Common::String> *Validation_Input1 =
  5771. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  5772. std::vector<WEX::Common::String> *Validation_Input2 =
  5773. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  5774. std::vector<WEX::Common::String> *Validation_Expected1 =
  5775. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  5776. // two expected outputs for any mode
  5777. std::vector<WEX::Common::String> *Validation_Expected2 =
  5778. &(handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable);
  5779. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5780. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5781. size_t count = Validation_Input1->size();
  5782. using namespace hlsl::DXIL;
  5783. Float32DenormMode mode = Float32DenormMode::Any;
  5784. if (strcmp(Arguments.m_psz, "-denorm preserve") == 0) {
  5785. mode = Float32DenormMode::Preserve;
  5786. }
  5787. else if (strcmp(Arguments.m_psz, "-denorm ftz") == 0) {
  5788. mode = Float32DenormMode::FTZ;
  5789. }
  5790. if (mode == Float32DenormMode::Any) {
  5791. DXASSERT(Validation_Expected2->size() == Validation_Expected1->size(),
  5792. "must have same number of expected values");
  5793. }
  5794. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5795. pDevice, m_support, pStream, "BinaryFPOp",
  5796. // this callbacked is called when the test
  5797. // is creating the resource to run the test
  5798. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5799. VERIFY_IS_TRUE(0 == _stricmp(Name, "SBinaryFPOp"));
  5800. size_t size = sizeof(SBinaryFPOp) * count;
  5801. Data.resize(size);
  5802. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)Data.data();
  5803. for (size_t i = 0; i < count; ++i) {
  5804. SBinaryFPOp *p = &pPrimitives[i];
  5805. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5806. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5807. float val1, val2;
  5808. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5809. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5810. p->input1 = val1;
  5811. p->input2 = val2;
  5812. }
  5813. // use shader from data table
  5814. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5815. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5816. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5817. });
  5818. MappedData data;
  5819. test->Test->GetReadBackData("SBinaryFPOp", &data);
  5820. SBinaryFPOp *pPrimitives = (SBinaryFPOp *)data.data();
  5821. WEX::TestExecution::DisableVerifyExceptions dve;
  5822. for (unsigned i = 0; i < count; ++i) {
  5823. SBinaryFPOp *p = &pPrimitives[i];
  5824. if (mode == Float32DenormMode::Any) {
  5825. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5826. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5827. float val1;
  5828. float val2;
  5829. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5830. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5831. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output = "
  5832. L"%6.8f, expected = %6.8f(%x) or %6.8f(%x)",
  5833. i, p->input1, p->input2, p->output1, val1, *(int *)&val1, val2, *(int *)&val2);
  5834. VERIFY_IS_TRUE(
  5835. CompareOutputWithExpectedValueFloat(
  5836. p->output1, val1, Validation_Type, Validation_Tolerance, mode) ||
  5837. CompareOutputWithExpectedValueFloat(
  5838. p->output1, val2, Validation_Type, Validation_Tolerance, mode));
  5839. }
  5840. else {
  5841. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5842. float val1;
  5843. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5844. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, output = "
  5845. L"%6.8f, expected = %6.8f(%a)",
  5846. i, p->input1, p->input2, p->output1, val1, *(int *)&val1);
  5847. VerifyOutputWithExpectedValueFloat(p->output1, val1, Validation_Type,
  5848. Validation_Tolerance, mode);
  5849. }
  5850. }
  5851. }
  5852. TEST_F(ExecutionTest, DenormTertiaryFloatOpTest) {
  5853. WEX::TestExecution::SetVerifyOutput verifySettings(
  5854. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  5855. CComPtr<IStream> pStream;
  5856. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  5857. CComPtr<ID3D12Device> pDevice;
  5858. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL::D3D_SHADER_MODEL_6_2)) {
  5859. return;
  5860. }
  5861. // Read data from the table
  5862. int tableSize = sizeof(DenormTertiaryFPOpParameters) / sizeof(TableParameter);
  5863. TableParameterHandler handler(DenormTertiaryFPOpParameters, tableSize);
  5864. CW2A Target(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  5865. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  5866. CW2A Arguments(handler.GetTableParamByName(L"ShaderOp.Arguments")->m_str);
  5867. std::vector<WEX::Common::String> *Validation_Input1 =
  5868. &(handler.GetTableParamByName(L"Validation.Input1")->m_StringTable);
  5869. std::vector<WEX::Common::String> *Validation_Input2 =
  5870. &(handler.GetTableParamByName(L"Validation.Input2")->m_StringTable);
  5871. std::vector<WEX::Common::String> *Validation_Input3 =
  5872. &(handler.GetTableParamByName(L"Validation.Input3")->m_StringTable);
  5873. std::vector<WEX::Common::String> *Validation_Expected1 =
  5874. &(handler.GetTableParamByName(L"Validation.Expected1")->m_StringTable);
  5875. // two expected outputs for any mode
  5876. std::vector<WEX::Common::String> *Validation_Expected2 =
  5877. &(handler.GetTableParamByName(L"Validation.Expected2")->m_StringTable);
  5878. LPCWSTR Validation_Type = handler.GetTableParamByName(L"Validation.Type")->m_str;
  5879. double Validation_Tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_double;
  5880. size_t count = Validation_Input1->size();
  5881. using namespace hlsl::DXIL;
  5882. Float32DenormMode mode = Float32DenormMode::Any;
  5883. if (strcmp(Arguments.m_psz, "-denorm preserve") == 0) {
  5884. mode = Float32DenormMode::Preserve;
  5885. }
  5886. else if (strcmp(Arguments.m_psz, "-denorm ftz") == 0) {
  5887. mode = Float32DenormMode::FTZ;
  5888. }
  5889. if (mode == Float32DenormMode::Any) {
  5890. DXASSERT(Validation_Expected2->size() == Validation_Expected1->size(),
  5891. "must have same number of expected values");
  5892. }
  5893. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  5894. pDevice, m_support, pStream, "TertiaryFPOp",
  5895. // this callbacked is called when the test
  5896. // is creating the resource to run the test
  5897. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  5898. VERIFY_IS_TRUE(0 == _stricmp(Name, "STertiaryFPOp"));
  5899. size_t size = sizeof(STertiaryFPOp) * count;
  5900. Data.resize(size);
  5901. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)Data.data();
  5902. for (size_t i = 0; i < count; ++i) {
  5903. STertiaryFPOp *p = &pPrimitives[i];
  5904. PCWSTR str1 = (*Validation_Input1)[i % Validation_Input1->size()];
  5905. PCWSTR str2 = (*Validation_Input2)[i % Validation_Input2->size()];
  5906. PCWSTR str3 = (*Validation_Input3)[i % Validation_Input3->size()];
  5907. float val1, val2, val3;
  5908. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5909. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5910. VERIFY_SUCCEEDED(ParseDataToFloat(str3, val3));
  5911. p->input1 = val1;
  5912. p->input2 = val2;
  5913. p->input3 = val3;
  5914. }
  5915. // use shader from data table
  5916. pShaderOp->Shaders.at(0).Target = Target.m_psz;
  5917. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  5918. pShaderOp->Shaders.at(0).Arguments = Arguments.m_psz;
  5919. });
  5920. MappedData data;
  5921. test->Test->GetReadBackData("STertiaryFPOp", &data);
  5922. STertiaryFPOp *pPrimitives = (STertiaryFPOp *)data.data();
  5923. WEX::TestExecution::DisableVerifyExceptions dve;
  5924. for (unsigned i = 0; i < count; ++i) {
  5925. STertiaryFPOp *p = &pPrimitives[i];
  5926. if (mode == Float32DenormMode::Any) {
  5927. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5928. LPCWSTR str2 = (*Validation_Expected2)[i % Validation_Expected2->size()];
  5929. float val1;
  5930. float val2;
  5931. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5932. VERIFY_SUCCEEDED(ParseDataToFloat(str2, val2));
  5933. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output = "
  5934. L"%6.8f, expected = %6.8f(%x) or %6.8f(%x)",
  5935. i, p->input1, p->input2, p->input3, p->output, val1, *(int *)&val1, val2, *(int *)&val2);
  5936. VERIFY_IS_TRUE(
  5937. CompareOutputWithExpectedValueFloat(
  5938. p->output, val1, Validation_Type, Validation_Tolerance, mode) ||
  5939. CompareOutputWithExpectedValueFloat(
  5940. p->output, val2, Validation_Type, Validation_Tolerance, mode));
  5941. }
  5942. else {
  5943. LPCWSTR str1 = (*Validation_Expected1)[i % Validation_Expected1->size()];
  5944. float val1;
  5945. VERIFY_SUCCEEDED(ParseDataToFloat(str1, val1));
  5946. LogCommentFmt(L"element #%u, input1 = %6.8f, input2 = %6.8f, input3 = %6.8f, output = "
  5947. L"%6.8f, expected = %6.8f(%a)",
  5948. i, p->input1, p->input2, p->input3, p->output, val1, *(int *)&val1);
  5949. VerifyOutputWithExpectedValueFloat(p->output, val1, Validation_Type,
  5950. Validation_Tolerance, mode);
  5951. }
  5952. }
  5953. }
  5954. // Setup for wave intrinsics tests
  5955. enum class ShaderOpKind {
  5956. WaveSum,
  5957. WaveProduct,
  5958. WaveActiveMax,
  5959. WaveActiveMin,
  5960. WaveCountBits,
  5961. WaveActiveAllEqual,
  5962. WaveActiveAnyTrue,
  5963. WaveActiveAllTrue,
  5964. WaveActiveBitOr,
  5965. WaveActiveBitAnd,
  5966. WaveActiveBitXor,
  5967. ShaderOpInvalid
  5968. };
  5969. struct ShaderOpKindPair {
  5970. LPCWSTR name;
  5971. ShaderOpKind kind;
  5972. };
  5973. static ShaderOpKindPair ShaderOpKindTable[] = {
  5974. { L"WaveActiveSum", ShaderOpKind::WaveSum },
  5975. { L"WaveActiveUSum", ShaderOpKind::WaveSum },
  5976. { L"WaveActiveProduct", ShaderOpKind::WaveProduct },
  5977. { L"WaveActiveUProduct", ShaderOpKind::WaveProduct },
  5978. { L"WaveActiveMax", ShaderOpKind::WaveActiveMax },
  5979. { L"WaveActiveUMax", ShaderOpKind::WaveActiveMax },
  5980. { L"WaveActiveMin", ShaderOpKind::WaveActiveMin },
  5981. { L"WaveActiveUMin", ShaderOpKind::WaveActiveMin },
  5982. { L"WaveActiveCountBits", ShaderOpKind::WaveCountBits },
  5983. { L"WaveActiveAllEqual", ShaderOpKind::WaveActiveAllEqual },
  5984. { L"WaveActiveAnyTrue", ShaderOpKind::WaveActiveAnyTrue },
  5985. { L"WaveActiveAllTrue", ShaderOpKind::WaveActiveAllTrue },
  5986. { L"WaveActiveBitOr", ShaderOpKind::WaveActiveBitOr },
  5987. { L"WaveActiveBitAnd", ShaderOpKind::WaveActiveBitAnd },
  5988. { L"WaveActiveBitXor", ShaderOpKind::WaveActiveBitXor },
  5989. { L"WavePrefixSum", ShaderOpKind::WaveSum },
  5990. { L"WavePrefixUSum", ShaderOpKind::WaveSum },
  5991. { L"WavePrefixProduct", ShaderOpKind::WaveProduct },
  5992. { L"WavePrefixUProduct", ShaderOpKind::WaveProduct },
  5993. { L"WavePrefixMax", ShaderOpKind::WaveActiveMax },
  5994. { L"WavePrefixUMax", ShaderOpKind::WaveActiveMax },
  5995. { L"WavePrefixMin", ShaderOpKind::WaveActiveMin },
  5996. { L"WavePrefixUMin", ShaderOpKind::WaveActiveMin },
  5997. { L"WavePrefixCountBits", ShaderOpKind::WaveCountBits }
  5998. };
  5999. ShaderOpKind GetShaderOpKind(LPCWSTR str) {
  6000. for (size_t i = 0; i < sizeof(ShaderOpKindTable)/sizeof(ShaderOpKindPair); ++i) {
  6001. if (_wcsicmp(ShaderOpKindTable[i].name, str) == 0) {
  6002. return ShaderOpKindTable[i].kind;
  6003. }
  6004. }
  6005. DXASSERT_ARGS(false, "Invalid ShaderOp name: %s", str);
  6006. return ShaderOpKind::ShaderOpInvalid;
  6007. }
  6008. template <typename InType, typename OutType, ShaderOpKind kind>
  6009. struct computeExpected {
  6010. OutType operator()(const std::vector<InType> &inputs,
  6011. const std::vector<int> &masks, int maskValue,
  6012. unsigned int index) {
  6013. return 0;
  6014. }
  6015. };
  6016. template <typename InType, typename OutType>
  6017. struct computeExpected<InType, OutType, ShaderOpKind::WaveSum> {
  6018. OutType operator()(const std::vector<InType> &inputs,
  6019. const std::vector<int> &masks, int maskValue,
  6020. unsigned int index) {
  6021. OutType sum = 0;
  6022. for (size_t i = 0; i < index; ++i) {
  6023. if (masks.at(i) == maskValue) {
  6024. sum += inputs.at(i);
  6025. }
  6026. }
  6027. return sum;
  6028. }
  6029. };
  6030. template <typename InType, typename OutType>
  6031. struct computeExpected<InType, OutType, ShaderOpKind::WaveProduct> {
  6032. OutType operator()(const std::vector<InType> &inputs,
  6033. const std::vector<int> &masks, int maskValue,
  6034. unsigned int index) {
  6035. OutType prod = 1;
  6036. for (size_t i = 0; i < index; ++i) {
  6037. if (masks.at(i) == maskValue) {
  6038. prod *= inputs.at(i);
  6039. }
  6040. }
  6041. return prod;
  6042. }
  6043. };
  6044. template <typename InType, typename OutType>
  6045. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax> {
  6046. OutType operator()(const std::vector<InType> &inputs,
  6047. const std::vector<int> &masks, int maskValue,
  6048. unsigned int index) {
  6049. OutType maximum = std::numeric_limits<OutType>::min();
  6050. for (size_t i = 0; i < index; ++i) {
  6051. if (masks.at(i) == maskValue && inputs.at(i) > maximum)
  6052. maximum = inputs.at(i);
  6053. }
  6054. return maximum;
  6055. }
  6056. };
  6057. template <typename InType, typename OutType>
  6058. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin> {
  6059. OutType operator()(const std::vector<InType> &inputs,
  6060. const std::vector<int> &masks, int maskValue,
  6061. unsigned int index) {
  6062. OutType minimum = std::numeric_limits<OutType>::max();
  6063. for (size_t i = 0; i < index; ++i) {
  6064. if (masks.at(i) == maskValue && inputs.at(i) < minimum)
  6065. minimum = inputs.at(i);
  6066. }
  6067. return minimum;
  6068. }
  6069. };
  6070. template <typename InType, typename OutType>
  6071. struct computeExpected<InType, OutType, ShaderOpKind::WaveCountBits> {
  6072. OutType operator()(const std::vector<InType> &inputs,
  6073. const std::vector<int> &masks, int maskValue,
  6074. unsigned int index) {
  6075. OutType count = 0;
  6076. for (size_t i = 0; i < index; ++i) {
  6077. if (masks.at(i) == maskValue && inputs.at(i) > 3) {
  6078. count++;
  6079. }
  6080. }
  6081. return count;
  6082. }
  6083. };
  6084. // In HLSL, boolean is represented in a 4 byte (uint32) format,
  6085. // So we cannot use c++ bool type to represent bool in HLSL
  6086. // HLSL returns 0 for false and 1 for true
  6087. template <typename InType, typename OutType>
  6088. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue> {
  6089. OutType operator()(const std::vector<InType> &inputs,
  6090. const std::vector<int> &masks, int maskValue,
  6091. unsigned int index) {
  6092. for (size_t i = 0; i < index; ++i) {
  6093. if (masks.at(i) == maskValue && inputs.at(i) != 0) {
  6094. return 1;
  6095. }
  6096. }
  6097. return 0;
  6098. }
  6099. };
  6100. template <typename InType, typename OutType>
  6101. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue> {
  6102. OutType operator()(const std::vector<InType> &inputs,
  6103. const std::vector<int> &masks, int maskValue,
  6104. unsigned int index) {
  6105. for (size_t i = 0; i < index; ++i) {
  6106. if (masks.at(i) == maskValue && inputs.at(i) == 0) {
  6107. return 0;
  6108. }
  6109. }
  6110. return 1;
  6111. }
  6112. };
  6113. template <typename InType, typename OutType>
  6114. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual> {
  6115. OutType operator()(const std::vector<InType> &inputs,
  6116. const std::vector<int> &masks, int maskValue,
  6117. unsigned int index) {
  6118. const InType *val = nullptr;
  6119. for (size_t i = 0; i < index; ++i) {
  6120. if (masks.at(i) == maskValue) {
  6121. if (val && *val != inputs.at(i)) {
  6122. return 0;
  6123. }
  6124. val = &inputs.at(i);
  6125. }
  6126. }
  6127. return 1;
  6128. }
  6129. };
  6130. template <typename InType, typename OutType>
  6131. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr> {
  6132. OutType operator()(const std::vector<InType> &inputs,
  6133. const std::vector<int> &masks, int maskValue,
  6134. unsigned int index) {
  6135. OutType bits = 0x00000000;
  6136. for (size_t i = 0; i < index; ++i) {
  6137. if (masks.at(i) == maskValue) {
  6138. bits |= inputs.at(i);
  6139. }
  6140. }
  6141. return bits;
  6142. }
  6143. };
  6144. template <typename InType, typename OutType>
  6145. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd> {
  6146. OutType operator()(const std::vector<InType> &inputs,
  6147. const std::vector<int> &masks, int maskValue,
  6148. unsigned int index) {
  6149. OutType bits = 0xffffffff;
  6150. for (size_t i = 0; i < index; ++i) {
  6151. if (masks.at(i) == maskValue) {
  6152. bits &= inputs.at(i);
  6153. }
  6154. }
  6155. return bits;
  6156. }
  6157. };
  6158. template <typename InType, typename OutType>
  6159. struct computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor> {
  6160. OutType operator()(const std::vector<InType> &inputs,
  6161. const std::vector<int> &masks, int maskValue,
  6162. unsigned int index) {
  6163. OutType bits = 0x00000000;
  6164. for (size_t i = 0; i < index; ++i) {
  6165. if (masks.at(i) == maskValue) {
  6166. bits ^= inputs.at(i);
  6167. }
  6168. }
  6169. return bits;
  6170. }
  6171. };
  6172. // Mask functions used to control active lanes
  6173. static int MaskAll(int i) {
  6174. UNREFERENCED_PARAMETER(i);
  6175. return 1;
  6176. }
  6177. static int MaskEveryOther(int i) {
  6178. return i % 2 == 0 ? 1 : 0;
  6179. }
  6180. static int MaskEveryThird(int i) {
  6181. return i % 3 == 0 ? 1 : 0;
  6182. }
  6183. typedef int(*MaskFunction)(int);
  6184. static MaskFunction MaskFunctionTable[] = {
  6185. MaskAll, MaskEveryOther, MaskEveryThird
  6186. };
  6187. template <typename InType, typename OutType>
  6188. static OutType computeExpectedWithShaderOp(const std::vector<InType> &inputs,
  6189. const std::vector<int> &masks,
  6190. int maskValue, unsigned int index,
  6191. LPCWSTR str) {
  6192. ShaderOpKind kind = GetShaderOpKind(str);
  6193. switch (kind) {
  6194. case ShaderOpKind::WaveSum:
  6195. return computeExpected<InType, OutType, ShaderOpKind::WaveSum>()(inputs, masks, maskValue, index);
  6196. case ShaderOpKind::WaveProduct:
  6197. return computeExpected<InType, OutType, ShaderOpKind::WaveProduct>()(inputs, masks, maskValue, index);
  6198. case ShaderOpKind::WaveActiveMax:
  6199. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMax>()(inputs, masks, maskValue, index);
  6200. case ShaderOpKind::WaveActiveMin:
  6201. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveMin>()(inputs, masks, maskValue, index);
  6202. case ShaderOpKind::WaveCountBits:
  6203. return computeExpected<InType, OutType, ShaderOpKind::WaveCountBits>()(inputs, masks, maskValue, index);
  6204. case ShaderOpKind::WaveActiveBitOr:
  6205. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitOr>()(inputs, masks, maskValue, index);
  6206. case ShaderOpKind::WaveActiveBitAnd:
  6207. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitAnd>()(inputs, masks, maskValue, index);
  6208. case ShaderOpKind::WaveActiveBitXor:
  6209. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveBitXor>()(inputs, masks, maskValue, index);
  6210. case ShaderOpKind::WaveActiveAnyTrue:
  6211. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAnyTrue>()(inputs, masks, maskValue, index);
  6212. case ShaderOpKind::WaveActiveAllTrue:
  6213. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllTrue>()(inputs, masks, maskValue, index);
  6214. case ShaderOpKind::WaveActiveAllEqual:
  6215. return computeExpected<InType, OutType, ShaderOpKind::WaveActiveAllEqual>()(inputs, masks, maskValue, index);
  6216. default:
  6217. DXASSERT_ARGS(false, "Invalid ShaderOp Name: %s", str);
  6218. return (OutType) 0;
  6219. }
  6220. };
  6221. // A framework for testing individual wave intrinsics tests.
  6222. // This test case is assuming that functions 1) WaveIsFirstLane and 2) WaveGetLaneIndex are correct for all lanes.
  6223. template <class T1, class T2>
  6224. void ExecutionTest::WaveIntrinsicsActivePrefixTest(
  6225. TableParameter *pParameterList, size_t numParameter, bool isPrefix) {
  6226. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6227. // Resource representation for compute shader
  6228. // firstLaneId is used to group different waves
  6229. // laneIndex is used to identify lane within the wave.
  6230. // Lane ids are not necessarily in same order as thread ids.
  6231. struct PerThreadData {
  6232. unsigned firstLaneId;
  6233. unsigned laneIndex;
  6234. int mask;
  6235. T1 input;
  6236. T2 output;
  6237. };
  6238. unsigned int NumThreadsX = 8;
  6239. unsigned int NumThreadsY = 12;
  6240. unsigned int NumThreadsZ = 1;
  6241. static const unsigned int ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  6242. static const unsigned int DispatchGroupCount = 1;
  6243. static const unsigned int ThreadCount = ThreadsPerGroup * DispatchGroupCount;
  6244. CComPtr<IStream> pStream;
  6245. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6246. CComPtr<ID3D12Device> pDevice;
  6247. if (!CreateDevice(&pDevice)) {
  6248. return;
  6249. }
  6250. if (!DoesDeviceSupportWaveOps(pDevice)) {
  6251. // Optional feature, so it's correct to not support it if declared as such.
  6252. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  6253. return;
  6254. }
  6255. TableParameterHandler handler(pParameterList, numParameter);
  6256. unsigned int numInputSet = handler.GetTableParamByName(L"Validation.NumInputSet")->m_uint;
  6257. // Obtain the list of input lists
  6258. std::vector<std::vector<T1>*> InputDataList;
  6259. for (unsigned int i = 0;
  6260. i < numInputSet; ++i) {
  6261. std::wstring inputName = L"Validation.InputSet";
  6262. inputName.append(std::to_wstring(i + 1));
  6263. InputDataList.push_back(handler.GetDataArray<T1>(inputName.data()));
  6264. }
  6265. CW2A Text(handler.GetTableParamByName(L"ShaderOp.text")->m_str);
  6266. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  6267. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  6268. // Running compute shader for each input set with different masks
  6269. for (size_t setIndex = 0; setIndex < numInputSet; ++setIndex) {
  6270. for (size_t maskIndex = 0; maskIndex < sizeof(MaskFunctionTable) / sizeof(MaskFunction); ++maskIndex) {
  6271. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(
  6272. pDevice, m_support, "WaveIntrinsicsOp",
  6273. // this callbacked is called when the test
  6274. // is creating the resource to run the test
  6275. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6276. VERIFY_IS_TRUE(0 == _stricmp(Name, "SWaveIntrinsicsOp"));
  6277. size_t size = sizeof(PerThreadData) * ThreadCount;
  6278. Data.resize(size);
  6279. PerThreadData *pPrimitives = (PerThreadData*)Data.data();
  6280. // 4 different inputs for each operation test
  6281. size_t index = 0;
  6282. std::vector<T1> *IntList = InputDataList[setIndex];
  6283. while (index < ThreadCount) {
  6284. PerThreadData *p = &pPrimitives[index];
  6285. p->firstLaneId = 0xFFFFBFFF;
  6286. p->laneIndex = 0xFFFFBFFF;
  6287. p->mask = MaskFunctionTable[maskIndex]((int)index);
  6288. p->input = (*IntList)[index % IntList->size()];
  6289. p->output = 0xFFFFBFFF;
  6290. index++;
  6291. }
  6292. // use shader from data table
  6293. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  6294. }, ShaderOpSet);
  6295. // Check the value
  6296. MappedData data;
  6297. test->Test->GetReadBackData("SWaveIntrinsicsOp", &data);
  6298. PerThreadData *pPrimitives = (PerThreadData*)data.data();
  6299. WEX::TestExecution::DisableVerifyExceptions dve;
  6300. // Grouping data by waves
  6301. std::vector<int> firstLaneIds;
  6302. for (size_t i = 0; i < ThreadCount; ++i) {
  6303. PerThreadData *p = &pPrimitives[i];
  6304. int firstLaneId = p->firstLaneId;
  6305. if (!contains(firstLaneIds, firstLaneId)) {
  6306. firstLaneIds.push_back(firstLaneId);
  6307. }
  6308. }
  6309. std::map<int, std::unique_ptr<std::vector<PerThreadData *>>> waves;
  6310. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  6311. waves[firstLaneIds.at(i)] = std::make_unique<std::vector<PerThreadData*>>();
  6312. }
  6313. for (size_t i = 0; i < ThreadCount; ++i) {
  6314. PerThreadData *p = &pPrimitives[i];
  6315. waves[p->firstLaneId].get()->push_back(p);
  6316. }
  6317. // validate for each wave
  6318. for (size_t i = 0; i < firstLaneIds.size(); ++i) {
  6319. // collect inputs and masks for a given wave
  6320. std::vector<PerThreadData *> *waveData = waves[firstLaneIds.at(i)].get();
  6321. std::vector<T1> inputList(waveData->size());
  6322. std::vector<int> maskList(waveData->size(), -1);
  6323. std::vector<T2> outputList(waveData->size());
  6324. // sort inputList and masklist by lane id. input for each lane can be computed for its group index
  6325. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  6326. unsigned laneID = waveData->at(j)->laneIndex;
  6327. // ensure that each lane ID is unique and within the range
  6328. VERIFY_IS_TRUE(0 <= laneID && laneID < waveData->size());
  6329. VERIFY_IS_TRUE(maskList.at(laneID) == -1);
  6330. maskList.at(laneID) = waveData->at(j)->mask;
  6331. inputList.at(laneID) = waveData->at(j)->input;
  6332. outputList.at(laneID) = waveData->at(j)->output;
  6333. }
  6334. std::wstring inputStr = L"Wave Inputs: ";
  6335. std::wstring maskStr = L"Wave Masks: ";
  6336. std::wstring outputStr = L"Wave Outputs: ";
  6337. // append input string and mask string in lane id order
  6338. for (size_t j = 0, end = waveData->size(); j < end; ++j) {
  6339. maskStr.append(std::to_wstring(maskList.at(j)));
  6340. maskStr.append(L" ");
  6341. inputStr.append(std::to_wstring(inputList.at(j)));
  6342. inputStr.append(L" ");
  6343. outputStr.append(std::to_wstring(outputList.at(j)));
  6344. outputStr.append(L" ");
  6345. }
  6346. LogCommentFmt(inputStr.data());
  6347. LogCommentFmt(maskStr.data());
  6348. LogCommentFmt(outputStr.data());
  6349. LogCommentFmt(L"\n");
  6350. // Compute expected output for a given inputs, masks, and index
  6351. for (size_t laneIndex = 0, laneEnd = inputList.size(); laneIndex < laneEnd; ++laneIndex) {
  6352. T2 expected;
  6353. // WaveActive is equivalent to WavePrefix lane # lane count
  6354. unsigned index = isPrefix ? (unsigned)laneIndex : (unsigned)inputList.size();
  6355. if (maskList.at(laneIndex) == 1) {
  6356. expected = computeExpectedWithShaderOp<T1, T2>(
  6357. inputList, maskList, 1, index,
  6358. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  6359. }
  6360. else {
  6361. expected = computeExpectedWithShaderOp<T1, T2>(
  6362. inputList, maskList, 0, index,
  6363. handler.GetTableParamByName(L"ShaderOp.Name")->m_str);
  6364. }
  6365. // TODO: use different comparison for floating point inputs
  6366. bool equal = outputList.at(laneIndex) == expected;
  6367. if (!equal) {
  6368. LogCommentFmt(L"lane%d: %4d, Expected : %4d", laneIndex, outputList.at(laneIndex), expected);
  6369. }
  6370. VERIFY_IS_TRUE(equal);
  6371. }
  6372. }
  6373. }
  6374. }
  6375. }
  6376. static const unsigned int MinWarpVersionForWaveIntrinsics = 16202;
  6377. TEST_F(ExecutionTest, WaveIntrinsicsActiveIntTest) {
  6378. if (GetTestParamUseWARP(true) &&
  6379. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6380. return;
  6381. }
  6382. WaveIntrinsicsActivePrefixTest<int, int>(
  6383. WaveIntrinsicsActiveIntParameters,
  6384. sizeof(WaveIntrinsicsActiveIntParameters) / sizeof(TableParameter),
  6385. /*isPrefix*/ false);
  6386. }
  6387. TEST_F(ExecutionTest, WaveIntrinsicsActiveUintTest) {
  6388. if (GetTestParamUseWARP(true) &&
  6389. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6390. return;
  6391. }
  6392. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  6393. WaveIntrinsicsActiveUintParameters,
  6394. sizeof(WaveIntrinsicsActiveUintParameters) / sizeof(TableParameter),
  6395. /*isPrefix*/ false);
  6396. }
  6397. TEST_F(ExecutionTest, WaveIntrinsicsPrefixIntTest) {
  6398. if (GetTestParamUseWARP(true) &&
  6399. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6400. return;
  6401. }
  6402. WaveIntrinsicsActivePrefixTest<int, int>(
  6403. WaveIntrinsicsPrefixIntParameters,
  6404. sizeof(WaveIntrinsicsPrefixIntParameters) / sizeof(TableParameter),
  6405. /*isPrefix*/ true);
  6406. }
  6407. TEST_F(ExecutionTest, WaveIntrinsicsPrefixUintTest) {
  6408. if (GetTestParamUseWARP(true) &&
  6409. !IsValidWarpDllVersion(MinWarpVersionForWaveIntrinsics)) {
  6410. return;
  6411. }
  6412. WaveIntrinsicsActivePrefixTest<unsigned int, unsigned int>(
  6413. WaveIntrinsicsPrefixUintParameters,
  6414. sizeof(WaveIntrinsicsPrefixUintParameters) / sizeof(TableParameter),
  6415. /*isPrefix*/ true);
  6416. }
  6417. template <typename T>
  6418. static T GetWaveMultiPrefixInitialAccumValue(LPCWSTR testName) {
  6419. if (_wcsicmp(testName, L"WaveMultiPrefixProduct") == 0 ||
  6420. _wcsicmp(testName, L"WaveMultiPrefixUProduct") == 0) {
  6421. return static_cast<T>(1);
  6422. } else if (_wcsicmp(testName, L"WaveMultiPrefixSum") == 0 ||
  6423. _wcsicmp(testName, L"WaveMultiPrefixUSum") == 0 ||
  6424. _wcsicmp(testName, L"WaveMultiPrefixBitOr") == 0 ||
  6425. _wcsicmp(testName, L"WaveMultiPrefixUBitOr") == 0 ||
  6426. _wcsicmp(testName, L"WaveMultiPrefixBitXor") == 0 ||
  6427. _wcsicmp(testName, L"WaveMultiPrefixUBitXor") == 0 ||
  6428. _wcsicmp(testName, L"WaveMultiPrefixCountBits") == 0 ||
  6429. _wcsicmp(testName, L"WaveMultiPrefixUCountBits") == 0) {
  6430. return static_cast<T>(0);
  6431. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitAnd") == 0 ||
  6432. _wcsicmp(testName, L"WaveMultiPrefixUBitAnd") == 0) {
  6433. return static_cast<T>(-1);
  6434. } else {
  6435. return static_cast<T>(0);
  6436. }
  6437. }
  6438. template <typename T>
  6439. std::function<T(T, T)> GetWaveMultiPrefixReferenceFunction(LPCWSTR testName) {
  6440. if (_wcsicmp(testName, L"WaveMultiPrefixProduct") == 0 ||
  6441. _wcsicmp(testName, L"WaveMultiPrefixUProduct") == 0) {
  6442. return [] (T lhs, T rhs) -> T { return lhs * rhs; };
  6443. } else if (_wcsicmp(testName, L"WaveMultiPrefixSum") == 0 ||
  6444. _wcsicmp(testName, L"WaveMultiPrefixUSum") == 0) {
  6445. return [] (T lhs, T rhs) -> T { return lhs + rhs; };
  6446. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitAnd") == 0 ||
  6447. _wcsicmp(testName, L"WaveMultiPrefixUBitAnd") == 0) {
  6448. return [] (T lhs, T rhs) -> T { return lhs & rhs; };
  6449. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitOr") == 0 ||
  6450. _wcsicmp(testName, L"WaveMultiPrefixUBitOr") == 0) {
  6451. return [] (T lhs, T rhs) -> T { return lhs | rhs; };
  6452. } else if (_wcsicmp(testName, L"WaveMultiPrefixBitXor") == 0 ||
  6453. _wcsicmp(testName, L"WaveMultiPrefixUBitXor") == 0) {
  6454. return [] (T lhs, T rhs) -> T { return lhs ^ rhs; };
  6455. } else if (_wcsicmp(testName, L"WaveMultiPrefixCountBits") == 0 ||
  6456. _wcsicmp(testName, L"WaveMultiPrefixUCountBits") == 0) {
  6457. // For CountBits, each lane contributes a boolean value. The test input is
  6458. // a zero or non-zero integer. If the input is a non-zero value then the
  6459. // condition is true, thus we contribute one to the bit count.
  6460. return [] (T lhs, T rhs) -> T { return lhs + (rhs ? 1 : 0); };
  6461. } else {
  6462. return [] (T lhs, T rhs) -> T { UNREFERENCED_PARAMETER(lhs); UNREFERENCED_PARAMETER(rhs); return 0; };
  6463. }
  6464. }
  6465. template <class T>
  6466. void
  6467. ExecutionTest::WaveIntrinsicsMultiPrefixOpTest(TableParameter *pParameterList,
  6468. size_t numParameters) {
  6469. WEX::TestExecution::SetVerifyOutput
  6470. verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6471. struct PerThreadData {
  6472. uint32_t key;
  6473. uint32_t firstLaneId;
  6474. uint32_t laneId;
  6475. uint32_t mask;
  6476. T value;
  6477. T result;
  6478. };
  6479. constexpr size_t NumThreadsX = 8;
  6480. constexpr size_t NumThreadsY = 12;
  6481. constexpr size_t NumThreadsZ = 1;
  6482. constexpr size_t ThreadsPerGroup = NumThreadsX * NumThreadsY * NumThreadsZ;
  6483. constexpr size_t DispatchGroupSize = 1;
  6484. constexpr size_t ThreadCount = ThreadsPerGroup * DispatchGroupSize;
  6485. CComPtr<IStream> pStream;
  6486. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6487. CComPtr<ID3D12Device> pDevice;
  6488. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_5)) {
  6489. return;
  6490. }
  6491. if (!DoesDeviceSupportWaveOps(pDevice)) {
  6492. // Optional feature, so it's correct to not support it if declared as such.
  6493. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  6494. return;
  6495. }
  6496. std::shared_ptr<st::ShaderOpSet>
  6497. ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  6498. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  6499. TableParameterHandler handler(pParameterList, numParameters);
  6500. CW2A shaderSource(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  6501. CW2A shaderProfile(handler.GetTableParamByName(L"ShaderOp.Target")->m_str);
  6502. auto testName = handler.GetTableParamByName(L"ShaderOp.Name")->m_str;
  6503. std::vector<T> *keys = handler.GetDataArray<T>(L"Validation.Keys");
  6504. std::vector<T> *values = handler.GetDataArray<T>(L"Validation.Values");
  6505. for (size_t maskIndex = 0; maskIndex < _countof(MaskFunctionTable); ++maskIndex) {
  6506. std::shared_ptr<ShaderOpTestResult> test =
  6507. RunShaderOpTestAfterParse(pDevice, m_support, "WaveIntrinsicsOp",
  6508. [&] (LPCSTR name, std::vector<BYTE> &data, st::ShaderOp *pShaderOp) {
  6509. UNREFERENCED_PARAMETER(name);
  6510. const size_t dataSize = sizeof(PerThreadData) * ThreadCount;
  6511. data.resize(dataSize);
  6512. PerThreadData *pThreadData = reinterpret_cast<PerThreadData *>(data.data());
  6513. for (size_t i = 0; i != ThreadCount; ++i) {
  6514. pThreadData[i].key = keys->at(i % keys->size());
  6515. pThreadData[i].value = values->at(i % values->size());
  6516. pThreadData[i].firstLaneId = 0xdeadbeef;
  6517. pThreadData[i].laneId = 0xdeadbeef;
  6518. pThreadData[i].mask = MaskFunctionTable[maskIndex]((int)i);
  6519. pThreadData[i].result = 0xdeadbeef;
  6520. }
  6521. pShaderOp->Shaders.at(0).Text = shaderSource;
  6522. pShaderOp->Shaders.at(0).Target = shaderProfile;
  6523. }, ShaderOpSet);
  6524. MappedData mappedData;
  6525. test->Test->GetReadBackData("SWaveIntrinsicsOp", &mappedData);
  6526. PerThreadData *resultData = reinterpret_cast<PerThreadData *>(mappedData.data());
  6527. // Partition our data into waves
  6528. std::map<uint32_t, std::vector<PerThreadData *>> waves;
  6529. for (size_t i = 0, e = ThreadCount; i != e; ++i) {
  6530. PerThreadData *elt = &resultData[i];
  6531. // Basic sanity checks
  6532. VERIFY_IS_TRUE(elt->firstLaneId != 0xdeadbeef);
  6533. VERIFY_IS_TRUE(elt->laneId != 0xdeadbeef);
  6534. waves[elt->firstLaneId].push_back(elt);
  6535. }
  6536. // Verify each wave
  6537. auto refFn = GetWaveMultiPrefixReferenceFunction<T>(testName);
  6538. for (auto &w : waves) {
  6539. std::vector<PerThreadData *> &waveData = w.second;
  6540. struct {
  6541. bool operator()(PerThreadData *a, PerThreadData *b) const {
  6542. return (a->laneId < b->laneId);
  6543. }
  6544. } compare;
  6545. // Need to sort based on the lane id
  6546. std::sort(waveData.begin(), waveData.end(), compare);
  6547. LogCommentFmt(L"LaneId Mask Key Value Result Expected");
  6548. LogCommentFmt(L"-------- -------- -------- -------- -------- --------");
  6549. for (size_t i = 0, e = waveData.size(); i != e; ++i) {
  6550. PerThreadData *data = waveData[i];
  6551. // Compute prefix operation over each previous lane element that has the
  6552. // same key value, and is part of the same active thread group
  6553. T accum = GetWaveMultiPrefixInitialAccumValue<T>(testName);
  6554. for (unsigned j = 0; j < i; ++j) {
  6555. if (waveData[j]->key == data->key && waveData[j]->mask == data->mask) {
  6556. accum = refFn(accum, waveData[j]->value);
  6557. }
  6558. }
  6559. LogCommentFmt(L"%08X %08X %08X %08X %08X %08X", data->laneId, data->mask, data->key, data->value, data->result, accum);
  6560. VERIFY_IS_TRUE(accum == data->result);
  6561. }
  6562. LogCommentFmt(L"\n");
  6563. }
  6564. }
  6565. }
  6566. TEST_F(ExecutionTest, WaveIntrinsicsSM65IntTest) {
  6567. WaveIntrinsicsMultiPrefixOpTest<int>(WaveIntrinsicsMultiPrefixIntParameters,
  6568. _countof(WaveIntrinsicsMultiPrefixIntParameters));
  6569. }
  6570. TEST_F(ExecutionTest, WaveIntrinsicsSM65UintTest) {
  6571. WaveIntrinsicsMultiPrefixOpTest<unsigned>(WaveIntrinsicsMultiPrefixUintParameters,
  6572. _countof(WaveIntrinsicsMultiPrefixUintParameters));
  6573. }
  6574. TEST_F(ExecutionTest, CBufferTestHalf) {
  6575. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6576. CComPtr<IStream> pStream;
  6577. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6578. // Single operation test at the moment.
  6579. CComPtr<ID3D12Device> pDevice;
  6580. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_2))
  6581. return;
  6582. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  6583. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  6584. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6585. return;
  6586. }
  6587. uint16_t InputData[] = { 0x3F80, 0x3F00, 0x3D80, 0x7BFF };
  6588. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "CBufferTestHalf",
  6589. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6590. UNREFERENCED_PARAMETER(pShaderOp);
  6591. VERIFY_IS_TRUE(0 == _stricmp(Name, "CB0"));
  6592. // use shader from data table.
  6593. Data.resize(sizeof(InputData));
  6594. uint16_t *pData = (uint16_t *)Data.data();
  6595. for (size_t i = 0; i < 4; ++i, ++pData) {
  6596. *pData = InputData[i];
  6597. }
  6598. });
  6599. {
  6600. MappedData data;
  6601. test->Test->GetReadBackData("RTarget", &data);
  6602. const uint16_t *pPixels = (uint16_t *)data.data();
  6603. for (int i = 0; i < 4; ++i) {
  6604. uint16_t output = *(pPixels + i);
  6605. float outputFloat = ConvertFloat16ToFloat32(output);
  6606. float inputFloat = ConvertFloat16ToFloat32(InputData[i]);
  6607. LogCommentFmt(L"element #%u: input = %6.8f(0x%04x), output = %6.8f(0x%04x)",
  6608. i, inputFloat, InputData[i], outputFloat, output);
  6609. VERIFY_ARE_EQUAL(inputFloat, outputFloat);
  6610. }
  6611. }
  6612. }
  6613. TEST_F(ExecutionTest, BarycentricsTest) {
  6614. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6615. CComPtr<IStream> pStream;
  6616. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6617. CComPtr<ID3D12Device> pDevice;
  6618. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_1))
  6619. return;
  6620. if (!DoesDeviceSupportBarycentrics(pDevice)) {
  6621. WEX::Logging::Log::Comment(L"Device does not support barycentrics.");
  6622. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6623. return;
  6624. }
  6625. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, "Barycentrics", nullptr);
  6626. MappedData data;
  6627. D3D12_RESOURCE_DESC &D = test->ShaderOp->GetResourceByName("RTarget")->Desc;
  6628. UINT width = (UINT)D.Width;
  6629. UINT height = D.Height;
  6630. UINT pixelSize = GetByteSizeForFormat(D.Format);
  6631. test->Test->GetReadBackData("RTarget", &data);
  6632. //const uint8_t *pPixels = (uint8_t *)data.data();
  6633. const float *pPixels = (float *)data.data();
  6634. // Get the vertex of barycentric coordinate using VBuffer
  6635. MappedData triangleData;
  6636. test->Test->GetReadBackData("VBuffer", &triangleData);
  6637. const float *pTriangleData = (float*)triangleData.data();
  6638. // get the size of the input data
  6639. unsigned triangleVertexSizeInFloat = 0;
  6640. for (auto element : test->ShaderOp->InputElements)
  6641. triangleVertexSizeInFloat += GetByteSizeForFormat(element.Format) / 4;
  6642. XMFLOAT2 p0(pTriangleData[0], pTriangleData[1]);
  6643. XMFLOAT2 p1(pTriangleData[triangleVertexSizeInFloat], pTriangleData[triangleVertexSizeInFloat + 1]);
  6644. XMFLOAT2 p2(pTriangleData[triangleVertexSizeInFloat * 2], pTriangleData[triangleVertexSizeInFloat * 2 + 1]);
  6645. XMFLOAT3 barycentricWeights[4] = {
  6646. XMFLOAT3(0.3333f, 0.3333f, 0.3333f),
  6647. XMFLOAT3(0.5f, 0.25f, 0.25f),
  6648. XMFLOAT3(0.25f, 0.5f, 0.25f),
  6649. XMFLOAT3(0.25f, 0.25f, 0.50f)
  6650. };
  6651. float tolerance = 0.001f;
  6652. for (unsigned i = 0; i < sizeof(barycentricWeights) / sizeof(XMFLOAT3); ++i) {
  6653. float w0 = barycentricWeights[i].x;
  6654. float w1 = barycentricWeights[i].y;
  6655. float w2 = barycentricWeights[i].z;
  6656. float x1 = w0 * p0.x + w1 * p1.x + w2 * p2.x;
  6657. float y1 = w0 * p0.y + w1 * p1.y + w2 * p2.y;
  6658. // map from x1 y1 to rtv pixels
  6659. int pixelX = (int)((x1 + 1) * (width - 1) / 2);
  6660. int pixelY = (int)((1 - y1) * (height - 1) / 2);
  6661. int offset = pixelSize * (pixelX + pixelY * width) / sizeof(pPixels[0]);
  6662. LogCommentFmt(L"location %u %u, value %f, %f, %f", pixelX, pixelY, pPixels[offset], pPixels[offset + 1], pPixels[offset + 2]);
  6663. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset], w0, tolerance));
  6664. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset + 1], w1, tolerance));
  6665. VERIFY_IS_TRUE(CompareFloatEpsilon(pPixels[offset + 2], w2, tolerance));
  6666. }
  6667. //SavePixelsToFile(pPixels, DXGI_FORMAT_R32G32B32A32_FLOAT, width, height, L"barycentric.bmp");
  6668. }
  6669. static const char RawBufferTestShaderDeclarations[] =
  6670. "// Note: COMPONENT_TYPE and COMPONENT_SIZE will be defined via compiler option -D\r\n"
  6671. "typedef COMPONENT_TYPE scalar; \r\n"
  6672. "typedef vector<COMPONENT_TYPE, 2> vector2; \r\n"
  6673. "typedef vector<COMPONENT_TYPE, 3> vector3; \r\n"
  6674. "typedef vector<COMPONENT_TYPE, 4> vector4; \r\n"
  6675. "\r\n"
  6676. "struct TestData { \r\n"
  6677. " scalar v1; \r\n"
  6678. " vector2 v2; \r\n"
  6679. " vector3 v3; \r\n"
  6680. " vector4 v4; \r\n"
  6681. "}; \r\n"
  6682. "\r\n"
  6683. "struct UavData {\r\n"
  6684. " TestData input; \r\n"
  6685. " TestData output; \r\n"
  6686. " TestData srvOut; \r\n"
  6687. "}; \r\n"
  6688. "\r\n"
  6689. "ByteAddressBuffer srv0 : register(t0); \r\n"
  6690. "StructuredBuffer<TestData> srv1 : register(t1); \r\n"
  6691. "ByteAddressBuffer srv2 : register(t2); \r\n"
  6692. "StructuredBuffer<TestData> srv3 : register(t3); \r\n"
  6693. "\r\n"
  6694. "RWByteAddressBuffer uav0 : register(u0); \r\n"
  6695. "RWStructuredBuffer<UavData> uav1 : register(u1); \r\n"
  6696. "RWByteAddressBuffer uav2 : register(u2); \r\n"
  6697. "RWStructuredBuffer<UavData> uav3 : register(u3); \r\n";
  6698. static const char RawBufferTestShaderBody[] =
  6699. " // offset of 'out' in 'UavData'\r\n"
  6700. " const int out_offset = COMPONENT_SIZE * 10; \r\n"
  6701. "\r\n"
  6702. " // offset of 'srv_out' in 'UavData'\r\n"
  6703. " const int srv_out_offset = COMPONENT_SIZE * 10 * 2; \r\n"
  6704. "\r\n"
  6705. " // offsets within the 'Data' struct\r\n"
  6706. " const int v1_offset = 0; \r\n"
  6707. " const int v2_offset = COMPONENT_SIZE; \r\n"
  6708. " const int v3_offset = COMPONENT_SIZE * 3; \r\n"
  6709. " const int v4_offset = COMPONENT_SIZE * 6; \r\n"
  6710. "\r\n"
  6711. " uav0.Store(srv_out_offset + v1_offset, srv0.Load<scalar>(v1_offset)); \r\n"
  6712. " uav0.Store(srv_out_offset + v2_offset, srv0.Load<vector2>(v2_offset)); \r\n"
  6713. " uav0.Store(srv_out_offset + v3_offset, srv0.Load<vector3>(v3_offset)); \r\n"
  6714. " uav0.Store(srv_out_offset + v4_offset, srv0.Load<vector4>(v4_offset)); \r\n"
  6715. "\r\n"
  6716. " uav1[0].srvOut.v1 = srv1[0].v1; \r\n"
  6717. " uav1[0].srvOut.v2 = srv1[0].v2; \r\n"
  6718. " uav1[0].srvOut.v3 = srv1[0].v3; \r\n"
  6719. " uav1[0].srvOut.v4 = srv1[0].v4; \r\n"
  6720. "\r\n"
  6721. " uav2.Store(srv_out_offset + v1_offset, srv2.Load<scalar>(v1_offset)); \r\n"
  6722. " uav2.Store(srv_out_offset + v2_offset, srv2.Load<vector2>(v2_offset)); \r\n"
  6723. " uav2.Store(srv_out_offset + v3_offset, srv2.Load<vector3>(v3_offset)); \r\n"
  6724. " uav2.Store(srv_out_offset + v4_offset, srv2.Load<vector4>(v4_offset)); \r\n"
  6725. "\r\n"
  6726. " uav3[0].srvOut.v1 = srv3[0].v1; \r\n"
  6727. " uav3[0].srvOut.v2 = srv3[0].v2; \r\n"
  6728. " uav3[0].srvOut.v3 = srv3[0].v3; \r\n"
  6729. " uav3[0].srvOut.v4 = srv3[0].v4; \r\n"
  6730. "\r\n"
  6731. " uav0.Store(out_offset + v1_offset, uav0.Load<scalar>(v1_offset)); \r\n"
  6732. " uav0.Store(out_offset + v2_offset, uav0.Load<vector2>(v2_offset)); \r\n"
  6733. " uav0.Store(out_offset + v3_offset, uav0.Load<vector3>(v3_offset)); \r\n"
  6734. " uav0.Store(out_offset + v4_offset, uav0.Load<vector4>(v4_offset)); \r\n"
  6735. "\r\n"
  6736. " uav1[0].output.v1 = uav1[0].input.v1; \r\n"
  6737. " uav1[0].output.v2 = uav1[0].input.v2; \r\n"
  6738. " uav1[0].output.v3 = uav1[0].input.v3; \r\n"
  6739. " uav1[0].output.v4 = uav1[0].input.v4; \r\n"
  6740. "\r\n"
  6741. " uav2.Store(out_offset + v1_offset, uav2.Load<scalar>(v1_offset)); \r\n"
  6742. " uav2.Store(out_offset + v2_offset, uav2.Load<vector2>(v2_offset)); \r\n"
  6743. " uav2.Store(out_offset + v3_offset, uav2.Load<vector3>(v3_offset)); \r\n"
  6744. " uav2.Store(out_offset + v4_offset, uav2.Load<vector4>(v4_offset)); \r\n"
  6745. "\r\n"
  6746. " uav3[0].output.v1 = uav3[0].input.v1; \r\n"
  6747. " uav3[0].output.v2 = uav3[0].input.v2; \r\n"
  6748. " uav3[0].output.v3 = uav3[0].input.v3; \r\n"
  6749. " uav3[0].output.v4 = uav3[0].input.v4; \r\n";
  6750. static const char RawBufferTestComputeShaderTemplate[] =
  6751. "%s\r\n" // <- RawBufferTestShaderDeclarations
  6752. "[numthreads(1, 1, 1)]\r\n"
  6753. "void main(uint GI : SV_GroupIndex) {\r\n"
  6754. "%s\r\n" // <- RawBufferTestShaderBody
  6755. "};";
  6756. static const char RawBufferTestGraphicsPixelShaderTemplate[] =
  6757. "%s\r\n" // <- RawBufferTestShaderDeclarations
  6758. "struct PSInput { \r\n"
  6759. " float4 pos : SV_POSITION; \r\n"
  6760. "}; \r\n"
  6761. "uint4 main(PSInput input) : SV_TARGET{ \r\n"
  6762. " if (input.pos.x + input.pos.y == 1.0f) { // pixel { 0.5, 0.5, 0 } \r\n"
  6763. "%s\r\n" // <- RawBufferTestShaderBody
  6764. " } \r\n"
  6765. " return uint4(1, 2, 3, 4); \r\n"
  6766. "};";
  6767. TEST_F(ExecutionTest, ComputeRawBufferLdStI32) {
  6768. RawBufferLdStTestData<int32_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT32 / 2 } };
  6769. RunComputeRawBufferLdStTest<int32_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I32, "ComputeRawBufferLdSt32Bit", data);
  6770. }
  6771. TEST_F(ExecutionTest, ComputeRawBufferLdStFloat) {
  6772. RawBufferLdStTestData<float> data = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, -105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6773. RunComputeRawBufferLdStTest<float>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Float, "ComputeRawBufferLdSt32Bit", data);
  6774. }
  6775. TEST_F(ExecutionTest, ComputeRawBufferLdStI64) {
  6776. RawBufferLdStTestData<int64_t> data = { { 1 }, { 2, -1 }, { 256, -105171532, 980 }, { 465, 13, -89, MAXUINT64 / 2 } };
  6777. RunComputeRawBufferLdStTest<int64_t>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "ComputeRawBufferLdSt64Bit", data);
  6778. }
  6779. TEST_F(ExecutionTest, ComputeRawBufferLdStDouble) {
  6780. RawBufferLdStTestData<double> data = { { 3e-10 }, { 1.5, -1.99988 }, { 256.0, -105.17, 980.0 }, { 465.1652, -1.5694e2, -0.8543e-2, 1333.5 } };
  6781. RunComputeRawBufferLdStTest<double>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "ComputeRawBufferLdSt64Bit", data);
  6782. }
  6783. TEST_F(ExecutionTest, ComputeRawBufferLdStI16) {
  6784. RawBufferLdStTestData<int16_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT16 / 2 } };
  6785. RunComputeRawBufferLdStTest<int16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I16, "ComputeRawBufferLdSt16Bit", data);
  6786. }
  6787. TEST_F(ExecutionTest, ComputeRawBufferLdStHalf) {
  6788. RawBufferLdStTestData<float> floatData = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, 105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6789. RawBufferLdStTestData<uint16_t> halfData;
  6790. for (int i = 0; i < sizeof(floatData)/sizeof(float); i++) {
  6791. ((uint16_t*)&halfData)[i] = ConvertFloat32ToFloat16(((float*)&floatData)[i]);
  6792. }
  6793. RunComputeRawBufferLdStTest<uint16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Half, "ComputeRawBufferLdSt16Bit", halfData);
  6794. }
  6795. TEST_F(ExecutionTest, GraphicsRawBufferLdStI32) {
  6796. RawBufferLdStTestData<int32_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT32 / 2 } };
  6797. RunGraphicsRawBufferLdStTest<int32_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I32, "GraphicsRawBufferLdSt32Bit", data);
  6798. }
  6799. TEST_F(ExecutionTest, GraphicsRawBufferLdStFloat) {
  6800. RawBufferLdStTestData<float> data = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, -105.17f, 980.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6801. RunGraphicsRawBufferLdStTest<float>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Float, "GraphicsRawBufferLdSt32Bit", data);
  6802. }
  6803. TEST_F(ExecutionTest, GraphicsRawBufferLdStI64) {
  6804. RawBufferLdStTestData<int64_t> data = { { 1 }, { 2, -1 }, { 256, -105171532, 980 }, { 465, 13, -89, MAXUINT64 / 2 } };
  6805. RunGraphicsRawBufferLdStTest<int64_t>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::I64, "GraphicsRawBufferLdSt64Bit", data);
  6806. }
  6807. TEST_F(ExecutionTest, GraphicsRawBufferLdStDouble) {
  6808. RawBufferLdStTestData<double> data = { { 3e-10 }, { 1.5, -1.99988 }, { 256.0, -105.17, 980.0 }, { 465.1652, -1.5694e2, -0.8543e-2, 1333.5 } };
  6809. RunGraphicsRawBufferLdStTest<double>(D3D_SHADER_MODEL_6_3, RawBufferLdStType::Double, "GraphicsRawBufferLdSt64Bit", data);
  6810. }
  6811. TEST_F(ExecutionTest, GraphicsRawBufferLdStI16) {
  6812. RawBufferLdStTestData<int16_t> data = { { 1 }, { 2, -1 }, { 256, -10517, 980 }, { 465, 13, -89, MAXUINT16 / 2 } };
  6813. RunGraphicsRawBufferLdStTest<int16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::I16, "GraphicsRawBufferLdSt16Bit", data);
  6814. }
  6815. TEST_F(ExecutionTest, GraphicsRawBufferLdStHalf) {
  6816. RawBufferLdStTestData<float> floatData = { { 3e-10f }, { 1.5f, -1.99988f }, { 256.0f, 105.17f, 0.0f }, { 465.1652f, -1.5694e2f, -0.8543e-2f, 1333.5f } };
  6817. RawBufferLdStTestData<uint16_t> halfData;
  6818. for (int i = 0; i < sizeof(floatData) / sizeof(float); i++) {
  6819. ((uint16_t*)&halfData)[i] = ConvertFloat32ToFloat16(((float*)&floatData)[i]);
  6820. }
  6821. RunGraphicsRawBufferLdStTest<uint16_t>(D3D_SHADER_MODEL_6_2, RawBufferLdStType::Half, "GraphicsRawBufferLdSt16Bit", halfData);
  6822. }
  6823. bool ExecutionTest::SetupRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6824. CComPtr<ID3D12Device> &pDevice, CComPtr<IStream> &pStream,
  6825. char *&sTy, char *&additionalOptions) {
  6826. if (!CreateDevice(&pDevice, shaderModel)) {
  6827. return false;
  6828. }
  6829. additionalOptions = "";
  6830. switch (dataType) {
  6831. case RawBufferLdStType::I64:
  6832. if (!DoesDeviceSupportInt64(pDevice)) {
  6833. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  6834. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6835. return false;
  6836. }
  6837. sTy = "int64_t";
  6838. break;
  6839. case RawBufferLdStType::Double:
  6840. if (!DoesDeviceSupportDouble(pDevice)) {
  6841. WEX::Logging::Log::Comment(L"Device does not support double operations.");
  6842. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6843. return false;
  6844. }
  6845. sTy = "double";
  6846. break;
  6847. case RawBufferLdStType::I16:
  6848. case RawBufferLdStType::Half:
  6849. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  6850. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  6851. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  6852. return false;
  6853. }
  6854. additionalOptions = "-enable-16bit-types";
  6855. sTy = (dataType == RawBufferLdStType::I16 ? "int16_t" : "half");
  6856. break;
  6857. case RawBufferLdStType::I32:
  6858. sTy = "int32_t";
  6859. break;
  6860. case RawBufferLdStType::Float:
  6861. sTy = "float";
  6862. break;
  6863. default:
  6864. DXASSERT_NOMSG("Invalid RawBufferLdStType");
  6865. }
  6866. // read shader config
  6867. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  6868. return true;
  6869. }
  6870. template <class Ty>
  6871. void ExecutionTest::VerifyRawBufferLdStTestResults(const std::shared_ptr<st::ShaderOpTest> test, const RawBufferLdStTestData<Ty> &testData) {
  6872. // read buffers back & verify expected values
  6873. static const int UavBufferCount = 4;
  6874. char bufferName[11] = "UAVBufferX";
  6875. for (unsigned i = 0; i < UavBufferCount; i++) {
  6876. MappedData dataUav;
  6877. RawBufferLdStUavData<Ty> *pOutData;
  6878. bufferName[sizeof(bufferName) - 2] = (char)(i + '0');
  6879. test->GetReadBackData(bufferName, &dataUav);
  6880. VERIFY_ARE_EQUAL(sizeof(RawBufferLdStUavData<Ty>), dataUav.size());
  6881. pOutData = (RawBufferLdStUavData<Ty> *)dataUav.data();
  6882. LogCommentFmt(L"Verifying UAVBuffer%d Load -> UAVBuffer%d Store", i, i);
  6883. // scalar
  6884. VERIFY_ARE_EQUAL(pOutData->output.v1, testData.v1);
  6885. // vector 2
  6886. VERIFY_ARE_EQUAL(pOutData->output.v2[0], testData.v2[0]);
  6887. VERIFY_ARE_EQUAL(pOutData->output.v2[1], testData.v2[1]);
  6888. // vector 3
  6889. VERIFY_ARE_EQUAL(pOutData->output.v3[0], testData.v3[0]);
  6890. VERIFY_ARE_EQUAL(pOutData->output.v3[1], testData.v3[1]);
  6891. VERIFY_ARE_EQUAL(pOutData->output.v3[2], testData.v3[2]);
  6892. // vector 4
  6893. VERIFY_ARE_EQUAL(pOutData->output.v4[0], testData.v4[0]);
  6894. VERIFY_ARE_EQUAL(pOutData->output.v4[1], testData.v4[1]);
  6895. VERIFY_ARE_EQUAL(pOutData->output.v4[2], testData.v4[2]);
  6896. VERIFY_ARE_EQUAL(pOutData->output.v4[3], testData.v4[3]);
  6897. // verify SRV Store
  6898. LogCommentFmt(L"Verifying SRVBuffer%d Load -> UAVBuffer%d Store", i, i);
  6899. // scalar
  6900. VERIFY_ARE_EQUAL(pOutData->srvOut.v1, testData.v1);
  6901. // vector 2
  6902. VERIFY_ARE_EQUAL(pOutData->srvOut.v2[0], testData.v2[0]);
  6903. VERIFY_ARE_EQUAL(pOutData->srvOut.v2[1], testData.v2[1]);
  6904. // vector 3
  6905. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[0], testData.v3[0]);
  6906. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[1], testData.v3[1]);
  6907. VERIFY_ARE_EQUAL(pOutData->srvOut.v3[2], testData.v3[2]);
  6908. // vector 4
  6909. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[0], testData.v4[0]);
  6910. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[1], testData.v4[1]);
  6911. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[2], testData.v4[2]);
  6912. VERIFY_ARE_EQUAL(pOutData->srvOut.v4[3], testData.v4[3]);
  6913. }
  6914. }
  6915. template <class Ty>
  6916. void ExecutionTest::RunComputeRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6917. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData) {
  6918. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6919. CComPtr<ID3D12Device> pDevice;
  6920. CComPtr<IStream> pStream;
  6921. char *sTy = nullptr, *additionalOptions = nullptr;
  6922. if (!SetupRawBufferLdStTest(shaderModel, dataType, pDevice, pStream, sTy, additionalOptions)) {
  6923. return;
  6924. }
  6925. // format shader source
  6926. char rawBufferTestShaderText[sizeof(RawBufferTestComputeShaderTemplate) + sizeof(RawBufferTestShaderDeclarations) + sizeof(RawBufferTestShaderBody)];
  6927. VERIFY_IS_TRUE(sprintf_s(rawBufferTestShaderText, sizeof(rawBufferTestShaderText),
  6928. RawBufferTestComputeShaderTemplate, RawBufferTestShaderDeclarations, RawBufferTestShaderBody) != -1);
  6929. // format compiler args
  6930. char compilerOptions[256];
  6931. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D COMPONENT_TYPE=%s -D COMPONENT_SIZE=%d %s", sTy, (int)sizeof(Ty), additionalOptions) != -1);
  6932. // run the shader
  6933. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, shaderOpName,
  6934. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6935. VERIFY_IS_TRUE(((0 == strncmp(Name, "SRVBuffer", 9)) || (0 == strncmp(Name, "UAVBuffer", 9))) &&
  6936. (Name[9] >= '0' && Name[9] <= '3'));
  6937. pShaderOp->Shaders.at(0).Arguments = compilerOptions;
  6938. pShaderOp->Shaders.at(0).Text = rawBufferTestShaderText;
  6939. VERIFY_IS_TRUE(sizeof(RawBufferLdStTestData<Ty>) <= Data.size());
  6940. RawBufferLdStTestData<Ty> *pInData = (RawBufferLdStTestData<Ty>*)Data.data();
  6941. memcpy(pInData, &testData, sizeof(RawBufferLdStTestData<Ty>));
  6942. });
  6943. // verify expected values
  6944. VerifyRawBufferLdStTestResults<Ty>(test->Test, testData);
  6945. }
  6946. template <class Ty>
  6947. void ExecutionTest::RunGraphicsRawBufferLdStTest(D3D_SHADER_MODEL shaderModel, RawBufferLdStType dataType,
  6948. const char *shaderOpName, const RawBufferLdStTestData<Ty> &testData) {
  6949. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  6950. CComPtr<ID3D12Device> pDevice;
  6951. CComPtr<IStream> pStream;
  6952. char *sTy = nullptr, *additionalOptions = nullptr;
  6953. if (!SetupRawBufferLdStTest(shaderModel, dataType, pDevice, pStream, sTy, additionalOptions)) {
  6954. return;
  6955. }
  6956. // format shader source
  6957. char rawBufferTestPixelShaderText[sizeof(RawBufferTestGraphicsPixelShaderTemplate) + sizeof(RawBufferTestShaderDeclarations) + sizeof(RawBufferTestShaderBody)];
  6958. VERIFY_IS_TRUE(sprintf_s(rawBufferTestPixelShaderText, sizeof(rawBufferTestPixelShaderText),
  6959. RawBufferTestGraphicsPixelShaderTemplate, RawBufferTestShaderDeclarations, RawBufferTestShaderBody) != -1);
  6960. // format compiler args
  6961. char compilerOptions[256];
  6962. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D COMPONENT_TYPE=%s -D COMPONENT_SIZE=%d %s", sTy, (int)sizeof(Ty), additionalOptions) != -1);
  6963. // run the shader
  6964. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(pDevice, m_support, pStream, shaderOpName,
  6965. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  6966. VERIFY_IS_TRUE(((0 == strncmp(Name, "SRVBuffer", 9)) || (0 == strncmp(Name, "UAVBuffer", 9))) &&
  6967. (Name[9] >= '0' && Name[9] <= '3'));
  6968. // pixel shader is at index 1, vertex shader at index 0
  6969. pShaderOp->Shaders.at(1).Arguments = compilerOptions;
  6970. pShaderOp->Shaders.at(1).Text = rawBufferTestPixelShaderText;
  6971. VERIFY_IS_TRUE(sizeof(RawBufferLdStTestData<Ty>) <= Data.size());
  6972. RawBufferLdStTestData<Ty> *pInData = (RawBufferLdStTestData<Ty>*)Data.data();
  6973. memcpy(pInData, &testData, sizeof(RawBufferLdStTestData<Ty>));
  6974. });
  6975. // verify expected values
  6976. VerifyRawBufferLdStTestResults<Ty>(test->Test, testData);
  6977. }
  6978. template<typename T>
  6979. uint32_t pack(std::array<T, 4> unpackedVals)
  6980. {
  6981. uint32_t dst = 0;
  6982. constexpr uint32_t bitMask = 0xFF;
  6983. for (uint32_t i = 0U; i < 4U; ++i)
  6984. {
  6985. dst |= (unpackedVals[i] & bitMask) << (i * 8);
  6986. }
  6987. return dst;
  6988. }
  6989. template <typename T>
  6990. uint32_t pack_clamp_u8(std::array<T, 4> unpackedVals)
  6991. {
  6992. int32_t clamp_min = std::numeric_limits<uint8_t>::min();
  6993. int32_t clamp_max = std::numeric_limits<uint8_t>::max();
  6994. uint32_t dst = 0;
  6995. for (uint32_t i = 0U; i < 4U; ++i)
  6996. {
  6997. int32_t clamped = std::min(std::max((int32_t)unpackedVals[i], clamp_min), clamp_max);
  6998. dst |= ((uint8_t)clamped) << (i * 8);
  6999. }
  7000. return dst;
  7001. }
  7002. template <typename T>
  7003. uint32_t pack_clamp_s8(std::array<T, 4> unpackedVals)
  7004. {
  7005. int32_t clamp_min = std::numeric_limits<int8_t>::min();
  7006. int32_t clamp_max = std::numeric_limits<int8_t>::max();
  7007. uint32_t dst = 0;
  7008. for (uint32_t i = 0U; i < 4U; ++i)
  7009. {
  7010. int32_t clamped = std::min(std::max((int32_t)unpackedVals[i], clamp_min), clamp_max);
  7011. dst |= ((uint8_t)clamped) << (i * 8);
  7012. }
  7013. return dst;
  7014. }
  7015. template<typename T>
  7016. std::array<T, 4> unpack_u(uint32_t packedVal)
  7017. {
  7018. std::array<T, 4> ret;
  7019. ret[0] = (uint8_t)((packedVal & 0x000000FF) >> 0 );
  7020. ret[1] = (uint8_t)((packedVal & 0x0000FF00) >> 8 );
  7021. ret[2] = (uint8_t)((packedVal & 0x00FF0000) >> 16);
  7022. ret[3] = (uint8_t)((packedVal & 0xFF000000) >> 24);
  7023. return ret;
  7024. }
  7025. template<typename T>
  7026. std::array<T, 4> unpack_s(uint32_t packedVal)
  7027. {
  7028. std::array<T, 4> ret;
  7029. ret[0] = (int8_t)((packedVal & 0x000000FF) >> 0 );
  7030. ret[1] = (int8_t)((packedVal & 0x0000FF00) >> 8 );
  7031. ret[2] = (int8_t)((packedVal & 0x00FF0000) >> 16);
  7032. ret[3] = (int8_t)((packedVal & 0xFF000000) >> 24);
  7033. return ret;
  7034. }
  7035. TEST_F(ExecutionTest, PackUnpackTest) {
  7036. WEX::TestExecution::SetVerifyOutput verifySettings(
  7037. WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7038. CComPtr<IStream> pStream;
  7039. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7040. CComPtr<ID3D12Device> pDevice;
  7041. #ifdef PACKUNPACK_PLACEHOLDER
  7042. string args = "-enable-16bit-types -DPACKUNPACK_PLACEHOLDER";
  7043. string target = "cs_6_2";
  7044. if (!CreateDevice(&pDevice)) {
  7045. return;
  7046. }
  7047. #else
  7048. string args = "-enable-16bit-types";
  7049. string target = "cs_6_6";
  7050. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6)) {
  7051. return;
  7052. }
  7053. #endif
  7054. if (!DoesDeviceSupportNative16bitOps(pDevice)) {
  7055. WEX::Logging::Log::Comment(L"Device does not support native 16-bit operations.");
  7056. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7057. return;
  7058. }
  7059. int tableSize = sizeof(PackUnpackOpParameters) / sizeof(TableParameter);
  7060. TableParameterHandler handler(PackUnpackOpParameters, tableSize);
  7061. CW2A Text(handler.GetTableParamByName(L"ShaderOp.Text")->m_str);
  7062. std::vector<uint32_t> *validation_input = &handler.GetTableParamByName(L"Validation.Input")->m_uint32Table;
  7063. uint32_t validation_tolerance = handler.GetTableParamByName(L"Validation.Tolerance")->m_uint;
  7064. size_t count = validation_input->size();
  7065. std::vector<SPackUnpackOpOutPacked> expectedPacked(count / 4);
  7066. std::vector<SPackUnpackOpOutUnpacked> expectedUnpacked(count / 4);
  7067. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTest(
  7068. pDevice, m_support, pStream, "PackUnpackOp",
  7069. // this callback is called when the test
  7070. // is creating the resource to run the test
  7071. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  7072. if (0 == _stricmp(Name, "g_bufIn"))
  7073. {
  7074. size_t size = sizeof(uint32_t) * 4 * count;
  7075. Data.resize(size);
  7076. uint32_t *pPrimitives = (uint32_t*)Data.data();
  7077. for (size_t i = 0; i < count / 4; ++i) {
  7078. uint32_t *p = &pPrimitives[i * 4];
  7079. uint32_t x = (*validation_input)[i * 4 + 0];
  7080. uint32_t y = (*validation_input)[i * 4 + 1];
  7081. uint32_t z = (*validation_input)[i * 4 + 2];
  7082. uint32_t w = (*validation_input)[i * 4 + 3];
  7083. p[0] = x;
  7084. p[1] = y;
  7085. p[2] = z;
  7086. p[3] = w;
  7087. std::array<uint32_t, 4> inputUint32 = { x, y, z, w };
  7088. std::array<int32_t, 4> inputInt32 = { (int32_t)x, (int32_t)y, (int32_t)z, (int32_t)w };
  7089. std::array<uint16_t, 4> inputUint16 = { (uint16_t)x, (uint16_t)y, (uint16_t)z, (uint16_t)w };
  7090. std::array<int16_t, 4> inputInt16 = { (int16_t)x, (int16_t)y, (int16_t)z, (int16_t)w };
  7091. // Pack unclamped
  7092. expectedPacked[i].packedUint32 = pack(inputUint32);
  7093. expectedPacked[i].packedInt32 = pack(inputInt32);
  7094. expectedPacked[i].packedUint16 = pack(inputUint16);
  7095. expectedPacked[i].packedInt16 = pack(inputInt16);
  7096. // pack clamped
  7097. expectedPacked[i].packedClampedUint32 = pack_clamp_u8(inputInt32);
  7098. expectedPacked[i].packedClampedInt32 = pack_clamp_s8(inputInt32);
  7099. expectedPacked[i].packedClampedUint16 = pack_clamp_u8(inputInt16);
  7100. expectedPacked[i].packedClampedInt16 = pack_clamp_s8(inputInt16);
  7101. // unpack
  7102. expectedUnpacked[i].outputUint32 = unpack_u<uint32_t>(expectedPacked[i].packedUint32);
  7103. expectedUnpacked[i].outputInt32 = unpack_s<int32_t >(expectedPacked[i].packedInt32 );
  7104. expectedUnpacked[i].outputUint16 = unpack_u<uint16_t>(expectedPacked[i].packedUint16);
  7105. expectedUnpacked[i].outputInt16 = unpack_s<int16_t >(expectedPacked[i].packedInt16 );
  7106. expectedUnpacked[i].outputClampedUint32 = unpack_u<uint32_t>(expectedPacked[i].packedClampedUint32);
  7107. expectedUnpacked[i].outputClampedInt32 = unpack_s<int32_t >(expectedPacked[i].packedClampedInt32 );
  7108. expectedUnpacked[i].outputClampedUint16 = unpack_u<uint16_t>(expectedPacked[i].packedClampedUint16);
  7109. expectedUnpacked[i].outputClampedInt16 = unpack_s<int16_t >(expectedPacked[i].packedClampedInt16 );
  7110. }
  7111. }
  7112. else
  7113. {
  7114. std::fill(Data.begin(), Data.end(), (BYTE)0);
  7115. }
  7116. // use shader from data table
  7117. pShaderOp->Shaders.at(0).Target = target.c_str();
  7118. pShaderOp->Shaders.at(0).Text = Text.m_psz;
  7119. pShaderOp->Shaders.at(0).Arguments = args.c_str();
  7120. });
  7121. MappedData packedData;
  7122. test->Test->GetReadBackData("g_bufOutPacked", &packedData);
  7123. SPackUnpackOpOutPacked *readBackPacked = (SPackUnpackOpOutPacked *)packedData.data();
  7124. MappedData unpackedData;
  7125. test->Test->GetReadBackData("g_bufOutPackedUnpacked", &unpackedData);
  7126. SPackUnpackOpOutUnpacked *readBackUnpacked = (SPackUnpackOpOutUnpacked *)unpackedData.data();
  7127. for (size_t i = 0; i < count / 4; ++i)
  7128. {
  7129. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedUint32, expectedPacked[i].packedUint32, validation_tolerance);
  7130. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedInt32 , expectedPacked[i].packedInt32 , validation_tolerance);
  7131. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedUint16, expectedPacked[i].packedUint16, validation_tolerance);
  7132. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedInt16 , expectedPacked[i].packedInt16 , validation_tolerance);
  7133. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedClampedUint32, expectedPacked[i].packedClampedUint32, validation_tolerance);
  7134. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedClampedInt32 , expectedPacked[i].packedClampedInt32 , validation_tolerance);
  7135. VerifyOutputWithExpectedValueUInt(readBackPacked[i].packedClampedUint16, expectedPacked[i].packedClampedUint16, validation_tolerance);
  7136. VerifyOutputWithExpectedValueInt (readBackPacked[i].packedClampedInt16 , expectedPacked[i].packedClampedInt16 , validation_tolerance);
  7137. for (uint32_t j = 0; j < 4; ++j)
  7138. {
  7139. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputUint32[j], expectedUnpacked[i].outputUint32[j], validation_tolerance);
  7140. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputInt32 [j], expectedUnpacked[i].outputInt32 [j], validation_tolerance);
  7141. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputUint16[j], expectedUnpacked[i].outputUint16[j], validation_tolerance);
  7142. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputInt16 [j], expectedUnpacked[i].outputInt16 [j], validation_tolerance);
  7143. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputClampedUint32[j], expectedUnpacked[i].outputClampedUint32[j], validation_tolerance);
  7144. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputClampedInt32 [j], expectedUnpacked[i].outputClampedInt32 [j], validation_tolerance);
  7145. VerifyOutputWithExpectedValueUInt(readBackUnpacked[i].outputClampedUint16[j], expectedUnpacked[i].outputClampedUint16[j], validation_tolerance);
  7146. VerifyOutputWithExpectedValueInt (readBackUnpacked[i].outputClampedInt16 [j], expectedUnpacked[i].outputClampedInt16 [j], validation_tolerance);
  7147. }
  7148. }
  7149. }
  7150. // This test expects a <pShader> that retrieves a signal value from each of a few
  7151. // resources that are initialized here. <isDynamic> determines if it uses the
  7152. // 6.6 Dynamic Resources feature.
  7153. // Values are read back from the result UAV and compared to the expected signals
  7154. void ExecutionTest::RunResourceTest(ID3D12Device *pDevice, const char *pShader,
  7155. const wchar_t *sm, bool isDynamic) {
  7156. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7157. const int NumSRVs = 3;
  7158. const int NumUAVs = 4;
  7159. const int NumResources = NumSRVs + NumUAVs;
  7160. const int NumSamplers = 2;
  7161. const int valueSize = 16;
  7162. static const int DispatchGroupX = 1;
  7163. static const int DispatchGroupY = 1;
  7164. static const int DispatchGroupZ = 1;
  7165. CComPtr<ID3D12GraphicsCommandList> pCommandList;
  7166. CComPtr<ID3D12CommandQueue> pCommandQueue;
  7167. CComPtr<ID3D12CommandAllocator> pCommandAllocator;
  7168. FenceObj FO;
  7169. UINT valueSizeInBytes = valueSize * sizeof(float);
  7170. CreateComputeCommandQueue(pDevice, L"DynamicResourcesTest Command Queue", &pCommandQueue);
  7171. InitFenceObj(pDevice, &FO);
  7172. // Create root signature.
  7173. CComPtr<ID3D12RootSignature> pRootSignature;
  7174. if (!isDynamic) {
  7175. // Not dynamic, create a range for each resource and from them, the root signature
  7176. CD3DX12_DESCRIPTOR_RANGE ranges[NumResources];
  7177. CD3DX12_DESCRIPTOR_RANGE srange[NumSamplers];
  7178. for (int i = 0; i < NumSRVs; i++)
  7179. ranges[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, i, 0);
  7180. for (int i = NumSRVs; i < NumResources; i++)
  7181. ranges[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_UAV, 1, i - NumSRVs, 0);
  7182. for (int i = 0; i < NumSamplers; i++)
  7183. srange[i].Init(D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER, 1, i, 0);
  7184. CreateRootSignatureFromRanges(pDevice, &pRootSignature, ranges, NumResources, srange, NumSamplers);
  7185. } else {
  7186. // Dynamic just requires the flags indicating that the builtin arrays should be accessible
  7187. #if !defined(D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED)
  7188. #define D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED (D3D12_ROOT_SIGNATURE_FLAGS)0x400
  7189. #define D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED (D3D12_ROOT_SIGNATURE_FLAGS)0x800
  7190. #endif
  7191. CD3DX12_ROOT_SIGNATURE_DESC rootSignatureDesc;
  7192. rootSignatureDesc.Init(0, nullptr, 0, nullptr,
  7193. D3D12_ROOT_SIGNATURE_FLAG_CBV_SRV_UAV_HEAP_DIRECTLY_INDEXED |
  7194. D3D12_ROOT_SIGNATURE_FLAG_SAMPLER_HEAP_DIRECTLY_INDEXED);
  7195. CreateRootSignatureFromDesc(pDevice, &rootSignatureDesc, &pRootSignature);
  7196. }
  7197. // Create pipeline state object.
  7198. CComPtr<ID3D12PipelineState> pComputeState;
  7199. CreateComputePSO(pDevice, pRootSignature, pShader, sm, &pComputeState);
  7200. // Create a command allocator and list for compute.
  7201. VERIFY_SUCCEEDED(pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_COMPUTE, IID_PPV_ARGS(&pCommandAllocator)));
  7202. VERIFY_SUCCEEDED(pDevice->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_COMPUTE, pCommandAllocator, pComputeState, IID_PPV_ARGS(&pCommandList)));
  7203. // Set up SRV resources
  7204. CComPtr<ID3D12Resource> pSRVResources[NumSRVs];
  7205. CComPtr<ID3D12Resource> pUAVResources[NumUAVs];
  7206. CComPtr<ID3D12Resource> pUploadResources[NumResources];
  7207. {
  7208. D3D12_RESOURCE_DESC bufDesc = CD3DX12_RESOURCE_DESC::Buffer(valueSizeInBytes);
  7209. float values[valueSize];
  7210. for (int i = 0; i < NumSRVs - 1; i++) {
  7211. for (int j = 0; j < valueSize; j++)
  7212. values[j] = 10.0f + i;
  7213. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, bufDesc,
  7214. &pSRVResources[i], &pUploadResources[i]);
  7215. }
  7216. D3D12_RESOURCE_DESC tex2dDesc = CD3DX12_RESOURCE_DESC::Tex2D(DXGI_FORMAT_R32_FLOAT, 4, 4);
  7217. for (int j = 0; j < valueSize; j++)
  7218. values[j] = 10.0 + (NumSRVs - 1);
  7219. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, tex2dDesc,
  7220. &pSRVResources[NumSRVs - 1], &pUploadResources[NumSRVs - 1]);
  7221. }
  7222. // Set up UAV resources
  7223. CComPtr<ID3D12Resource> pReadBuffer;
  7224. float values[valueSize];
  7225. for (int i = 0; i < NumUAVs - 2; i++) {
  7226. for (int j = 0; j < valueSize; j++)
  7227. values[j] = 20.0f + i;
  7228. CreateTestUavs(pDevice, pCommandList, values, valueSizeInBytes,
  7229. &pUAVResources[i], &pUploadResources[NumSRVs + i]);
  7230. }
  7231. for (int j = 0; j < valueSize; j++)
  7232. values[j] = 20.0 + (NumUAVs - 1);
  7233. CreateTestUavs(pDevice, pCommandList, values, valueSizeInBytes,
  7234. &pUAVResources[NumUAVs - 2], &pUploadResources[NumResources - 2], &pReadBuffer);
  7235. for (int j = 0; j < valueSize; j++)
  7236. values[j] = 20.0 + (NumUAVs - 2);
  7237. D3D12_RESOURCE_DESC tex1dDesc = CD3DX12_RESOURCE_DESC::Tex1D(DXGI_FORMAT_R32_FLOAT, valueSize, 1, 0, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS);
  7238. CreateTestResources(pDevice, pCommandList, values, valueSizeInBytes, tex1dDesc,
  7239. &pUAVResources[NumUAVs - 1], &pUploadResources[NumResources - 1]);
  7240. // Close the command list and execute it to perform the GPU setup.
  7241. pCommandList->Close();
  7242. ExecuteCommandList(pCommandQueue, pCommandList);
  7243. WaitForSignal(pCommandQueue, FO);
  7244. VERIFY_SUCCEEDED(pCommandAllocator->Reset());
  7245. VERIFY_SUCCEEDED(pCommandList->Reset(pCommandAllocator, pComputeState));
  7246. CComPtr<ID3D12DescriptorHeap> pResHeap;
  7247. CComPtr<ID3D12DescriptorHeap> pSampHeap;
  7248. CreateDefaultDescHeaps(pDevice, NumSRVs + NumUAVs, NumSamplers, &pResHeap, &pSampHeap);
  7249. // Create Rootsignature and descriptor tables
  7250. {
  7251. ID3D12DescriptorHeap *descHeaps[2] = {pResHeap, pSampHeap};
  7252. pCommandList->SetDescriptorHeaps(2, descHeaps);
  7253. pCommandList->SetComputeRootSignature(pRootSignature);
  7254. if (!isDynamic) {
  7255. // Only non-dynamic resources require descriptortables
  7256. pCommandList->SetComputeRootDescriptorTable(0, pResHeap->GetGPUDescriptorHandleForHeapStart());
  7257. pCommandList->SetComputeRootDescriptorTable(1, pSampHeap->GetGPUDescriptorHandleForHeapStart());
  7258. }
  7259. }
  7260. CD3DX12_CPU_DESCRIPTOR_HANDLE baseHandle(pResHeap->GetCPUDescriptorHandleForHeapStart());
  7261. // Create SRVs
  7262. CreateRawSRV(pDevice, baseHandle, valueSize, pSRVResources[0]);
  7263. CreateStructSRV(pDevice, baseHandle, valueSize, sizeof(float), pSRVResources[1]);
  7264. CreateTex2DSRV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pSRVResources[2]);
  7265. // Create UAVs
  7266. CreateRawUAV(pDevice, baseHandle, valueSize, pUAVResources[0]);
  7267. CreateStructUAV(pDevice, baseHandle, valueSize, sizeof(float), pUAVResources[1]);
  7268. CreateTypedUAV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pUAVResources[2]);
  7269. CreateTex1DUAV(pDevice, baseHandle, valueSize, DXGI_FORMAT_R32_FLOAT, pUAVResources[3]);
  7270. D3D12_FILTER filters[] = {D3D12_FILTER_MIN_MAG_LINEAR_MIP_POINT, D3D12_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT};
  7271. float borderColors[] = {30.0, 31.0};
  7272. CreateDefaultSamplers(pDevice, pSampHeap->GetCPUDescriptorHandleForHeapStart(),
  7273. filters, borderColors, NumSamplers);
  7274. // Run the compute shader and copy the results back to readable memory.
  7275. pCommandList->Dispatch(DispatchGroupX, DispatchGroupY, DispatchGroupZ);
  7276. RecordTransitionBarrier(pCommandList, pUAVResources[NumUAVs - 2], D3D12_RESOURCE_STATE_UNORDERED_ACCESS, D3D12_RESOURCE_STATE_COPY_SOURCE);
  7277. pCommandList->CopyResource(pReadBuffer, pUAVResources[NumUAVs - 2]);
  7278. pCommandList->Close();
  7279. ExecuteCommandList(pCommandQueue, pCommandList);
  7280. WaitForSignal(pCommandQueue, FO);
  7281. MappedData data(pReadBuffer, valueSize*sizeof(float));
  7282. const float *pData = (float*)data.data();
  7283. LogCommentFmt(L"Verify bound resources are properly selected");
  7284. VERIFY_ARE_EQUAL(pData[0], 10);
  7285. VERIFY_ARE_EQUAL(pData[1], 11);
  7286. VERIFY_ARE_EQUAL(pData[2], 12);
  7287. VERIFY_ARE_EQUAL(pData[3], 20);
  7288. VERIFY_ARE_EQUAL(pData[4], 21);
  7289. VERIFY_ARE_EQUAL(pData[5], 22);
  7290. VERIFY_ARE_EQUAL(pData[6], 30);
  7291. VERIFY_ARE_EQUAL(pData[7], 1); // samplecmp 1 means it matched 31
  7292. }
  7293. TEST_F(ExecutionTest, SignatureResourcesTest) {
  7294. std::string pShader =
  7295. "ByteAddressBuffer g_rawBuf : register(t0);\n"
  7296. "StructuredBuffer<float> g_structBuf : register(t1);\n"
  7297. "Texture2D<float> g_tex : register(t2);\n"
  7298. "RWByteAddressBuffer g_rwRawBuf : register(u0);\n"
  7299. "RWStructuredBuffer<float> g_rwStructBuf : register(u1);\n"
  7300. "RWBuffer<float> g_result : register(u2);\n"
  7301. "RWTexture1D<float> g_rwTex : register(u3);\n"
  7302. "SamplerState g_samp : register(s0);\n"
  7303. "SamplerComparisonState g_sampCmp : register(s1);\n"
  7304. "[NumThreads(1, 1, 1)]\n"
  7305. "void main(uint ix : SV_GroupIndex) {\n"
  7306. " g_result[0] = g_rawBuf.Load<float>(0);\n"
  7307. " g_result[1] = g_structBuf.Load(0);\n"
  7308. " g_result[2] = g_tex.Load(0);\n"
  7309. " g_result[3] = g_rwRawBuf.Load<float>(0);\n"
  7310. " g_result[4] = g_rwStructBuf.Load(0);\n"
  7311. " g_result[5] = g_rwTex.Load(0);\n"
  7312. " g_result[6] = g_tex.SampleLevel(g_samp, -0.5, 0);\n"
  7313. " g_result[7] = g_tex.SampleCmpLevelZero(g_sampCmp, -0.5, 31.0);\n"
  7314. "}\n";
  7315. CComPtr<ID3D12Device> pDevice;
  7316. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7317. return;
  7318. RunResourceTest(pDevice, pShader.c_str(), L"cs_6_6", /*isDynamic*/false);
  7319. }
  7320. TEST_F(ExecutionTest, DynamicResourcesTest) {
  7321. static const char pShader[] =
  7322. "static ByteAddressBuffer g_rawBuf = ResourceDescriptorHeap[0];\n"
  7323. "static StructuredBuffer<float> g_structBuf = ResourceDescriptorHeap[1];\n"
  7324. "static Texture2D<float> g_tex = ResourceDescriptorHeap[2];\n"
  7325. "static RWByteAddressBuffer g_rwRawBuf = ResourceDescriptorHeap[3];\n"
  7326. "static RWStructuredBuffer<float> g_rwStructBuf = ResourceDescriptorHeap[4];\n"
  7327. "static RWBuffer<float> g_result = ResourceDescriptorHeap[5];\n"
  7328. "static RWTexture1D<float> g_rwTex = ResourceDescriptorHeap[6];\n"
  7329. "static SamplerState g_samp = SamplerDescriptorHeap[0];\n"
  7330. "static SamplerComparisonState g_sampCmp = SamplerDescriptorHeap[1];\n"
  7331. "[NumThreads(1, 1, 1)]\n"
  7332. "void main(uint ix : SV_GroupIndex) {\n"
  7333. " g_result[0] = g_rawBuf.Load<float>(0);\n"
  7334. " g_result[1] = g_structBuf.Load(0);\n"
  7335. " g_result[2] = g_tex.Load(0);\n"
  7336. " g_result[3] = g_rwRawBuf.Load<float>(0);\n"
  7337. " g_result[4] = g_rwStructBuf.Load(0);\n"
  7338. " g_result[5] = g_rwTex.Load(0);\n"
  7339. " g_result[6] = g_tex.SampleLevel(g_samp, -0.5, 0);\n"
  7340. " g_result[7] = g_tex.SampleCmpLevelZero(g_sampCmp, -0.5, 31.0);\n"
  7341. "}\n";
  7342. CComPtr<ID3D12Device> pDevice;
  7343. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7344. return;
  7345. // ResourceDescriptorHeap/SamplerDescriptorHeap requires Resource Binding Tier 3
  7346. D3D12_FEATURE_DATA_D3D12_OPTIONS devOptions;
  7347. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS, &devOptions, sizeof(devOptions)));
  7348. if (devOptions.ResourceBindingTier < D3D12_RESOURCE_BINDING_TIER_3) {
  7349. WEX::Logging::Log::Comment(L"Device does not support Resource Binding Tier 3");
  7350. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7351. return;
  7352. }
  7353. RunResourceTest(pDevice, pShader, L"cs_6_6", /*isDynamic*/true);
  7354. }
  7355. #define MAX_WAVESIZE 128
  7356. #define strinfigy2(arg) #arg
  7357. #define strinfigy(arg) strinfigy2(arg)
  7358. void ExecutionTest::WaveSizeTest() {
  7359. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7360. CComPtr<ID3D12Device> pDevice;
  7361. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6)) {
  7362. return;
  7363. }
  7364. // Check Wave support
  7365. if (!DoesDeviceSupportWaveOps(pDevice)) {
  7366. // Optional feature, so it's correct to not support it if declared as such.
  7367. WEX::Logging::Log::Comment(L"Device does not support wave operations.");
  7368. return;
  7369. }
  7370. // Get supported wave sizes
  7371. D3D12_FEATURE_DATA_D3D12_OPTIONS1 waveOpts;
  7372. VERIFY_SUCCEEDED(pDevice->CheckFeatureSupport((D3D12_FEATURE)D3D12_FEATURE_D3D12_OPTIONS1, &waveOpts, sizeof(waveOpts)));
  7373. UINT minWaveSize = waveOpts.WaveLaneCountMin;
  7374. UINT maxWaveSize = waveOpts.WaveLaneCountMax;
  7375. DXASSERT_NOMSG(minWaveSize <= maxWaveSize);
  7376. DXASSERT((minWaveSize & (minWaveSize - 1)) == 0, "must be a power of 2");
  7377. DXASSERT((maxWaveSize & (maxWaveSize - 1)) == 0, "must be a power of 2");
  7378. // read shader config
  7379. CComPtr<IStream> pStream;
  7380. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  7381. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7382. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7383. // format shader source
  7384. const char waveSizeTestShader[] =
  7385. "struct TestData { \r\n"
  7386. " uint count; \r\n"
  7387. "}; \r\n"
  7388. "RWStructuredBuffer<TestData> data : register(u0); \r\n"
  7389. "\r\n"
  7390. "// Note: WAVESIZE will be defined via compiler option -D\r\n"
  7391. "[wavesize(WAVESIZE)]\r\n"
  7392. "[numthreads(" strinfigy(MAX_WAVESIZE) "*2,1,1)]\r\n"
  7393. "void main(uint3 tid : SV_DispatchThreadID ) { \r\n"
  7394. " data[tid.x].count = WaveActiveSum(1); \r\n"
  7395. "}\r\n";
  7396. struct WaveSizeTestData {
  7397. uint32_t count;
  7398. };
  7399. for (UINT waveSize = minWaveSize; waveSize <= maxWaveSize; waveSize *= 2) {
  7400. // format compiler args
  7401. char compilerOptions[32];
  7402. VERIFY_IS_TRUE(sprintf_s(compilerOptions, sizeof(compilerOptions), "-D WAVESIZE=%d", waveSize) != -1);
  7403. // run the shader
  7404. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "WaveSizeTest",
  7405. [&](LPCSTR Name, std::vector<BYTE> &Data, st::ShaderOp *pShaderOp) {
  7406. VERIFY_IS_TRUE((0 == strncmp(Name, "UAVBuffer0", 10)));
  7407. pShaderOp->Shaders.at(0).Arguments = compilerOptions;
  7408. pShaderOp->Shaders.at(0).Text = waveSizeTestShader;
  7409. VERIFY_IS_TRUE(sizeof(WaveSizeTestData)*MAX_WAVESIZE <= Data.size());
  7410. WaveSizeTestData *pInData = (WaveSizeTestData *)Data.data();
  7411. memset(&pInData, sizeof(WaveSizeTestData)*MAX_WAVESIZE, 0);
  7412. }, ShaderOpSet);
  7413. // verify expected values
  7414. MappedData dataUav;
  7415. WaveSizeTestData *pOutData;
  7416. test->Test->GetReadBackData("UAVBuffer0", &dataUav);
  7417. VERIFY_ARE_EQUAL(sizeof(WaveSizeTestData)*MAX_WAVESIZE, dataUav.size());
  7418. pOutData = (WaveSizeTestData*)dataUav.data();
  7419. LogCommentFmt(L"Verifying test result for wave size %d", waveSize);
  7420. for (unsigned i = 0; i < MAX_WAVESIZE; i++) {
  7421. if (!VERIFY_ARE_EQUAL(pOutData[i].count, waveSize))
  7422. break;
  7423. }
  7424. }
  7425. }
  7426. // Atomic operation testing
  7427. // Atomic tests take a single integer index as input and contort it into some
  7428. // kind of interesting contributor to the operation in question.
  7429. // So each vertex, pixel, thread, or other will have a unique index that produces
  7430. // a contributing value to the calculation which is stored in a small resource
  7431. // For arithmetic or bitwise operations, each contributor accumulates to the same
  7432. // location in the resource indexed by the operation type. Addition is in index 0
  7433. // umin/umax are in 1 and 2 and so on.
  7434. // To make sure that the most significant bits are involved in the calculation,
  7435. // particularly in the case of 64-bit values, each contributing value is duplicated
  7436. // to the lower and upper halves of the value. There is an exception to this when
  7437. // addition exceeds the available size and also for compare and exchange explained below.
  7438. // For compare and exchange operations, 64 output locations are shared by the various lanes.
  7439. // Each lane attempts to write to a location that is shared with several others.
  7440. // The first one to write to it determines its contents, which will be the lane index <ix>
  7441. // in the upper bits and the output location index in the lower bits.
  7442. // This ensures that the compare operations consider the upper bits in the comparison.
  7443. // The initial compare store is followed by a compare exchange that compares for the
  7444. // value the current lane would have assigned there. Finally, the output of the cmpxchg
  7445. // is used to determine if the current lane should perform the final unconditional exchange.
  7446. // The values are verified by checking the lower bits for the matching location index
  7447. // and ensuring that the upper bits undergoing the same transformation result in the location index.
  7448. // For lane index <ix> the location is calculated and final result assigned as if by this code:
  7449. // g_outputBuf[(ix/3)%64] = (ix << shBits) | ((ix/3)%64);
  7450. bool AtomicResultMatches(const BYTE *uResults, uint64_t gold, size_t size) {
  7451. if (memcmp(uResults, &gold, size)) {
  7452. if (size == 4)
  7453. LogCommentFmt(L" value %d is not %d", ((uint32_t*)uResults)[0], (uint32_t)gold);
  7454. else
  7455. LogCommentFmt(L" value %lld is not %lld", ((uint64_t*)uResults)[0], gold);
  7456. return false;
  7457. }
  7458. return true;
  7459. }
  7460. // Used to duplicate the lower half bits into the upper half bits of an integer
  7461. // To verify that the full value is being considered, many tests duplicate the results into the upper half
  7462. #define SHIFT(val, bits) (((val)&((1ULL<<(bits))-1ULL)) | ((uint64_t)(val) << (bits)))
  7463. // Symbolic constants for the results
  7464. #define ADD_IDX 0
  7465. #define UMIN_IDX 1
  7466. #define UMAX_IDX 2
  7467. #define AND_IDX 3
  7468. #define OR_IDX 4
  7469. #define XOR_IDX 5
  7470. #define SMIN_IDX 0
  7471. #define SMAX_IDX 1
  7472. // Verify results for atomic operations. <uResults> and <sResults> are pointers to
  7473. // the readback resource sections containing unsigned and signed integers respectively.
  7474. // <pXchg> is a poiner to the readback resource containing the results of the compare
  7475. // and exchange operations tests. <stride> is the number of bytes between results for
  7476. // all of the results pointers. <maxIdx> is the number of indices that went into the results
  7477. // which is used to determine what the results should be. <bitSize> is the size in bits of
  7478. // the produced results, either 32 or 64.
  7479. void VerifyAtomicResults(const BYTE *uResults, const BYTE *sResults,
  7480. const BYTE *pXchg, size_t stride, uint64_t maxIdx, size_t bitSize) {
  7481. // Each atomic test performs the test on the value in the lower half
  7482. // and also duplicated in the upper half of the value. The SHIFT macros account for this.
  7483. // This is to verify that the upper bits are considered
  7484. uint64_t shBits = bitSize/2;
  7485. size_t byteSize = bitSize/8;
  7486. // Test ADD Operation
  7487. // ADD just sums all the indices. The result should the sum of the highest and lowest indices
  7488. // multiplied by half the number of sums.
  7489. uint64_t addResult = (maxIdx)*(maxIdx-1)/2;
  7490. LogCommentFmt(L"Verifying %d-bit integer atomic add", bitSize);
  7491. // For 32-bit values, the sum exceeds the 16 bit limit, so we can't duplicate
  7492. // That's fine, the duplication is really for 64-bit values.
  7493. if (bitSize < 64)
  7494. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*ADD_IDX, addResult, byteSize));
  7495. else
  7496. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*ADD_IDX, SHIFT(addResult, shBits), byteSize));
  7497. // Test MIN and MAX Operations
  7498. // The result of a simple min and max of any sequence of indices would be fairly uninteresting
  7499. // and certain erroneous behavior might mistakenly produce the correct results.
  7500. // To make it interesting, the contributing values will change depending on the evenness of the index.
  7501. // On an even index, min and max operate on the bitflipped index. For signed compares, this is
  7502. // interpretted as a negative value and for unsigned, a very high value.
  7503. // For unsigned min/max, index 0 will be bitflipped to ~0, which is interpretted as the maximum
  7504. // Because zero is manipulated, this leaves 1 as the lowest value.
  7505. LogCommentFmt(L"Verifying %d-bit integer atomic umin", bitSize);
  7506. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*UMIN_IDX, SHIFT(1ULL, shBits), byteSize)); // UMin
  7507. LogCommentFmt(L"Verifying %d-bit integer atomic umax", bitSize);
  7508. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*UMAX_IDX, ~0ULL, byteSize)); // UMax
  7509. // For signed min/max, the index just before the last will be bitflipped (maxIndex is always even).
  7510. // This is interpretted as -(maxIndex-1) and will be the lowest
  7511. // The maxIndex will be unaltered and interpretted as the highest.
  7512. LogCommentFmt(L"Verifying %d-bit integer atomic smin", bitSize);
  7513. VERIFY_IS_TRUE(AtomicResultMatches(sResults + stride*SMIN_IDX, SHIFT(-((int64_t)maxIdx-1), shBits), byteSize)); // SMin
  7514. LogCommentFmt(L"Verifying %d-bit integer atomic smax", bitSize);
  7515. VERIFY_IS_TRUE(AtomicResultMatches(sResults + stride*SMAX_IDX, SHIFT(maxIdx-1, shBits), byteSize)); // SMax
  7516. // Test AND and OR operations.
  7517. // For AND operations, all indices are bitflipped and ANDed to the previous result.
  7518. // This means that the highest bits, which are never set by the contributing indices will be set
  7519. // for all the indices, so they will be set in the final result.
  7520. // For OR operations, the indices are ORed to the previous result unaltered
  7521. // This means that any bit that is set in any index will be set in the final OR result.
  7522. // In practice, this means that the cumulative result of the AND and OR operations
  7523. // are bitflipped versions of each other.
  7524. // Finding the most significant set bit by the max index or next power of two (pot)
  7525. // gives us the pivot point for these results
  7526. uint64_t nextPot = 1ULL << (bitSize - 1);
  7527. for (;nextPot && !((maxIdx-1) & (nextPot)); nextPot >>= 1) {}
  7528. nextPot <<= 1;
  7529. LogCommentFmt(L"Verifying %d-bit integer atomic and", bitSize);
  7530. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*AND_IDX, ~SHIFT(nextPot-1, shBits), byteSize)); // And
  7531. LogCommentFmt(L"Verifying %d-bit integer atomic or", bitSize);
  7532. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*OR_IDX, SHIFT(nextPot-1, shBits), byteSize)); // Or
  7533. // Test XOR operation
  7534. // For XOR operations, a 1 is shifted by the number of spaces equal to the index and XORed
  7535. // to the previous result. Because this would rapidely shift off the end of the value,
  7536. // giving undefined and uninteresting results, the index is moduloed to a value that will
  7537. // fit within the type size.
  7538. // Because many of the tests use total numbers of lanes that can be evenly divisible by 32 or 64,
  7539. // these values aren't used for the modulo since the expected result might be zero,
  7540. // which could be encountered through erroneous behavior.
  7541. // Instead, one less than the type size in bits is used for the modulo.
  7542. // Even though we don't know the actual order these operations are performed,
  7543. // indices that make up a contiguous sequence of 31 or 63 values can be thought of as one of a series of "passes".
  7544. // Each "pass" sets or clears the bits depending on what's already there.
  7545. // if the number of the pass is odd, the bits are being unset and all above the mod position should be set.
  7546. // If even, the bits are in the process of being set and bits below the mod position should be set.
  7547. uint64_t xorResult = ((1ULL<<((maxIdx)%(bitSize-1))) -1);
  7548. if (((maxIdx/(bitSize-1))&1)) {
  7549. xorResult ^= ~0ULL;
  7550. // The XOR above may set uninvolved upper bits, messing up the compare. So AND off the uninvolved bits.
  7551. xorResult &= ((1ULL<<(bitSize-1)) - 1);
  7552. }
  7553. LogCommentFmt(L"Verifying %d-bit integer atomic xor", bitSize);
  7554. VERIFY_IS_TRUE(AtomicResultMatches(uResults + stride*XOR_IDX, xorResult, byteSize));
  7555. // Test CMP/XCHG Operations
  7556. // This tests CompareStore, CompareExchange, and Exchange operations.
  7557. // Unlike above, every lane isn't contributing to the same resource location
  7558. // Instead, every lane competes with a few others to update the same resource location.
  7559. // The first lane to find the contents of their location uninitialized will
  7560. // update it. To verify that upper bits are considered in the comparison and
  7561. // in the assignment, the value stored in the lowest bits is the location index.
  7562. // This ensures that part will be the same for each of the competing lanes.
  7563. // The uppermost bits are updated with the index of the lane that got there first.
  7564. // Subsequent calls to CompareExchange will verify this value matches and alter
  7565. // the content slightly. Finally, a simple check of the output value to what
  7566. // the current lane would expect and a call to exchange will update the value once more
  7567. // To verify this has gone through properly, the upper portion is converted as
  7568. // if to calculate the location index and compared with the location index.
  7569. // It could be the index of any of several lanes that assign to that location,
  7570. // but this ensures that it is not any lane outside of that group.
  7571. // The lower bits are compared to the location index as well.
  7572. LogCommentFmt(L"Verifying %d-bit integer atomic cmp/xchg results", bitSize);
  7573. for (size_t i = 0; i < 64; i++) {
  7574. uint64_t val = *((uint64_t*)(pXchg + i*stride));
  7575. // Verify lower bits match location index exactly
  7576. VERIFY_ARE_EQUAL(i, val & ((1ULL << shBits) - 1ULL));
  7577. // Verify that upper bits contain original index that transforms to location index
  7578. VERIFY_ARE_EQUAL(((val >> shBits)/3)%64, i);
  7579. }
  7580. }
  7581. void VerifyAtomicsRawTest(std::shared_ptr<ShaderOpTestResult> test,
  7582. uint64_t maxIdx, size_t bitSize) {
  7583. size_t stride = 8;
  7584. // struct mirroring that in the shader
  7585. struct AtomicStuff {
  7586. float prepad[2][3];
  7587. UINT uintEl[4];
  7588. int sintEl[4];
  7589. struct useless {
  7590. uint32_t unused[3];
  7591. } postpad;
  7592. float last;
  7593. };
  7594. MappedData uintData, xchgData;
  7595. test->Test->GetReadBackData("U0", &uintData);
  7596. test->Test->GetReadBackData("U1", &xchgData);
  7597. const AtomicStuff *pStruct = (AtomicStuff *)uintData.data();
  7598. const AtomicStuff *pStrXchg = (AtomicStuff *)xchgData.data();
  7599. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWStructuredBuffer resource", bitSize);
  7600. VerifyAtomicResults((const BYTE*)&(pStruct[0].uintEl[2]), (const BYTE*)&(pStruct[1].sintEl[2]),
  7601. (const BYTE*)&(pStrXchg[0].uintEl[2]), sizeof(AtomicStuff), maxIdx, bitSize);
  7602. const BYTE *pUint = nullptr;
  7603. const BYTE *pXchg = nullptr;
  7604. test->Test->GetReadBackData("U2", &uintData);
  7605. test->Test->GetReadBackData("U3", &xchgData);
  7606. pUint = (BYTE *)uintData.data();
  7607. pXchg = (BYTE *)xchgData.data();
  7608. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWByteAddressBuffer resource", bitSize);
  7609. VerifyAtomicResults(pUint, pUint + stride*6,
  7610. pXchg, stride, maxIdx, bitSize);
  7611. }
  7612. void VerifyAtomicsTypedTest(std::shared_ptr<ShaderOpTestResult> test,
  7613. uint64_t maxIdx, size_t bitSize) {
  7614. size_t stride = 8;
  7615. MappedData uintData, sintData, xchgData;
  7616. const BYTE *pUint = nullptr;
  7617. const BYTE *pSint = nullptr;
  7618. const BYTE *pXchg = nullptr;
  7619. // Typed resources can't share between 32 and 64 bits
  7620. if (bitSize == 32) {
  7621. test->Test->GetReadBackData("U6", &uintData);
  7622. test->Test->GetReadBackData("U7", &sintData);
  7623. test->Test->GetReadBackData("U8", &xchgData);
  7624. } else {
  7625. test->Test->GetReadBackData("U12", &uintData);
  7626. test->Test->GetReadBackData("U13", &sintData);
  7627. test->Test->GetReadBackData("U14", &xchgData);
  7628. }
  7629. pUint = (BYTE *)uintData.data();
  7630. pSint = (BYTE *)sintData.data();
  7631. pXchg = (BYTE *)xchgData.data();
  7632. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWBuffer resource", bitSize);
  7633. VerifyAtomicResults(pUint, pSint + stride, pXchg, stride, maxIdx, bitSize);
  7634. // Typed resources can't share between 32 and 64 bits
  7635. if (bitSize == 32) {
  7636. test->Test->GetReadBackData("U9", &uintData);
  7637. test->Test->GetReadBackData("U10", &sintData);
  7638. test->Test->GetReadBackData("U11", &xchgData);
  7639. } else {
  7640. test->Test->GetReadBackData("U15", &uintData);
  7641. test->Test->GetReadBackData("U16", &sintData);
  7642. test->Test->GetReadBackData("U17", &xchgData);
  7643. }
  7644. pUint = (BYTE *)uintData.data();
  7645. pSint = (BYTE *)sintData.data();
  7646. pXchg = (BYTE *)xchgData.data();
  7647. LogCommentFmt(L"Verifying %d-bit integer atomic operations on RWTexture resource", bitSize);
  7648. VerifyAtomicResults(pUint, pSint + stride, pXchg, stride, maxIdx, bitSize);
  7649. }
  7650. void VerifyAtomicsSharedTest(std::shared_ptr<ShaderOpTestResult> test,
  7651. uint64_t maxIdx, size_t bitSize) {
  7652. size_t stride = 8;
  7653. MappedData uintData, xchgData;
  7654. const BYTE *pUint = nullptr;
  7655. const BYTE *pXchg = nullptr;
  7656. test->Test->GetReadBackData("U4", &uintData);
  7657. test->Test->GetReadBackData("U5", &xchgData);
  7658. pUint = (BYTE *)uintData.data();
  7659. pXchg = (BYTE *)xchgData.data();
  7660. LogCommentFmt(L"Verifying %d-bit integer atomic operations on groupshared variables", bitSize);
  7661. VerifyAtomicResults(pUint, pUint + stride*6,
  7662. pXchg, stride, maxIdx, bitSize);
  7663. }
  7664. void VerifyAtomicsTest(std::shared_ptr<ShaderOpTestResult> test,
  7665. uint64_t maxIdx, size_t bitSize) {
  7666. VerifyAtomicsRawTest(test, maxIdx, bitSize);
  7667. VerifyAtomicsTypedTest(test, maxIdx, bitSize);
  7668. }
  7669. TEST_F(ExecutionTest, AtomicsTest) {
  7670. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7671. CComPtr<IStream> pStream;
  7672. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7673. CComPtr<ID3D12Device> pDevice;
  7674. if (!CreateDevice(&pDevice))
  7675. return;
  7676. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7677. std::make_shared<st::ShaderOpSet>();
  7678. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7679. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("AtomicsHeap");
  7680. // Test compute shader
  7681. LogCommentFmt(L"Verifying 32-bit integer atomic operations in compute shader");
  7682. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7683. VerifyAtomicsTest(test, 32*32, 32);
  7684. VerifyAtomicsSharedTest(test, 32*32, 32);
  7685. // Test mesh shader if available
  7686. pShaderOp->CS = nullptr;
  7687. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7688. LogCommentFmt(L"Verifying 32-bit integer atomic operations in amp/mesh/pixel shaders");
  7689. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7690. VerifyAtomicsTest(test, 8*8*2 + 8*8*2 + 64*64, 32);
  7691. VerifyAtomicsSharedTest(test, 8*8*2 + 8*8*2, 32);
  7692. }
  7693. // Test Vertex + Pixel shader
  7694. pShaderOp->MS = nullptr;
  7695. LogCommentFmt(L"Verifying 32-bit integer atomic operations in vert/pixel shaders");
  7696. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7697. VerifyAtomicsTest(test, 64*64+6, 32);
  7698. }
  7699. TEST_F(ExecutionTest, Atomics64Test) {
  7700. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7701. CComPtr<IStream> pStream;
  7702. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7703. CComPtr<ID3D12Device> pDevice;
  7704. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7705. return;
  7706. if (!DoesDeviceSupportInt64(pDevice)) {
  7707. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7708. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7709. return;
  7710. }
  7711. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7712. std::make_shared<st::ShaderOpSet>();
  7713. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7714. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("AtomicsRoot");
  7715. // Reassign shader stages to 64-bit versions
  7716. // Collect 64-bit shaders
  7717. LPCSTR CS64 = nullptr, VS64 = nullptr, PS64 = nullptr;
  7718. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7719. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7720. if (!strcmp(S.Name, "CS")) CS64 = S.Name;
  7721. if (!strcmp(S.Name, "VS")) VS64 = S.Name;
  7722. if (!strcmp(S.Name, "PS")) PS64 = S.Name;
  7723. if (!strcmp(S.Name, "AS")) AS64 = S.Name;
  7724. if (!strcmp(S.Name, "MS")) MS64 = S.Name;
  7725. }
  7726. pShaderOp->CS = CS64;
  7727. pShaderOp->VS = VS64;
  7728. pShaderOp->PS = PS64;
  7729. pShaderOp->AS = AS64;
  7730. pShaderOp->MS = MS64;
  7731. // Test compute shader
  7732. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in compute shader");
  7733. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsRoot", nullptr, ShaderOpSet);
  7734. VerifyAtomicsRawTest(test, 32*32, 64);
  7735. // Test mesh shader if available
  7736. pShaderOp->CS = nullptr;
  7737. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7738. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in amp/mesh/pixel shader");
  7739. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsRoot", nullptr, ShaderOpSet);
  7740. VerifyAtomicsRawTest(test, 8*8*2 + 8*8*2 + 64*64, 64);
  7741. }
  7742. // Test Vertex + Pixel shader
  7743. pShaderOp->MS = nullptr;
  7744. LogCommentFmt(L"Verifying 64-bit integer atomic operations on raw buffers in vert/pixel shader");
  7745. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsRoot", nullptr, ShaderOpSet);
  7746. VerifyAtomicsRawTest(test, 64*64+6, 64);
  7747. }
  7748. TEST_F(ExecutionTest, AtomicsRawHeap64Test) {
  7749. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7750. CComPtr<IStream> pStream;
  7751. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7752. CComPtr<ID3D12Device> pDevice;
  7753. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7754. return;
  7755. if (!DoesDeviceSupportInt64(pDevice)) {
  7756. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7757. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7758. return;
  7759. }
  7760. if (!DoesDeviceSupportHeap64Atomics(pDevice)) {
  7761. WEX::Logging::Log::Comment(L"Device does not support 64-bit atomic operations on heap resources.");
  7762. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7763. return;
  7764. }
  7765. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7766. std::make_shared<st::ShaderOpSet>();
  7767. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7768. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("AtomicsHeap");
  7769. // Reassign shader stages to 64-bit versions
  7770. // Collect 64-bit shaders
  7771. LPCSTR CS64 = nullptr, VS64 = nullptr, PS64 = nullptr;
  7772. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7773. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7774. if (!strcmp(S.Name, "CS64")) CS64 = S.Name;
  7775. if (!strcmp(S.Name, "VS64")) VS64 = S.Name;
  7776. if (!strcmp(S.Name, "PS64")) PS64 = S.Name;
  7777. if (!strcmp(S.Name, "AS64")) AS64 = S.Name;
  7778. if (!strcmp(S.Name, "MS64")) MS64 = S.Name;
  7779. }
  7780. pShaderOp->CS = CS64;
  7781. pShaderOp->VS = VS64;
  7782. pShaderOp->PS = PS64;
  7783. pShaderOp->AS = AS64;
  7784. pShaderOp->MS = MS64;
  7785. // Test compute shader
  7786. LogCommentFmt(L"Verifying 64-bit integer atomic operations on heap raw buffers in compute shader");
  7787. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7788. VerifyAtomicsRawTest(test, 32*32, 64);
  7789. // Test mesh shader if available
  7790. pShaderOp->CS = nullptr;
  7791. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7792. LogCommentFmt(L"Verifying 64-bit integer atomic operations on heap raw buffers in amp/mesh/pixel shader");
  7793. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7794. VerifyAtomicsRawTest(test, 8*8*2 + 8*8*2 + 64*64, 64);
  7795. }
  7796. // Test Vertex + Pixel shader
  7797. pShaderOp->MS = nullptr;
  7798. LogCommentFmt(L"Verifying 64-bit integer atomic operations on heap raw buffers in vert/pixel shader");
  7799. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7800. VerifyAtomicsRawTest(test, 64*64+6, 64);
  7801. }
  7802. TEST_F(ExecutionTest, AtomicsTyped64Test) {
  7803. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7804. CComPtr<IStream> pStream;
  7805. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7806. CComPtr<ID3D12Device> pDevice;
  7807. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7808. return;
  7809. if (!DoesDeviceSupportInt64(pDevice)) {
  7810. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7811. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7812. return;
  7813. }
  7814. if (!DoesDeviceSupportTyped64Atomics(pDevice)) {
  7815. WEX::Logging::Log::Comment(L"Device does not support int64 atomic operations on typed resources.");
  7816. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7817. return;
  7818. }
  7819. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7820. std::make_shared<st::ShaderOpSet>();
  7821. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7822. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("AtomicsHeap");
  7823. // Reassign shader stages to 64-bit versions
  7824. // Collect 64-bit shaders
  7825. LPCSTR CS64 = nullptr, VS64 = nullptr, PS64 = nullptr;
  7826. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7827. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7828. if (!strcmp(S.Name, "CSTY64")) CS64 = S.Name;
  7829. if (!strcmp(S.Name, "VSTY64")) VS64 = S.Name;
  7830. if (!strcmp(S.Name, "PSTY64")) PS64 = S.Name;
  7831. if (!strcmp(S.Name, "ASTY64")) AS64 = S.Name;
  7832. if (!strcmp(S.Name, "MSTY64")) MS64 = S.Name;
  7833. }
  7834. pShaderOp->CS = CS64;
  7835. pShaderOp->VS = VS64;
  7836. pShaderOp->PS = PS64;
  7837. pShaderOp->AS = AS64;
  7838. pShaderOp->MS = MS64;
  7839. // Test compute shader
  7840. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in compute shader");
  7841. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7842. VerifyAtomicsTypedTest(test, 32*32, 64);
  7843. // Test mesh shader if available
  7844. pShaderOp->CS = nullptr;
  7845. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7846. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in amp/mesh/pixel shader");
  7847. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7848. VerifyAtomicsTypedTest(test, 8*8*2 + 8*8*2 + 64*64, 64);
  7849. }
  7850. // Test Vertex + Pixel shader
  7851. pShaderOp->MS = nullptr;
  7852. LogCommentFmt(L"Verifying 64-bit integer atomic operations on typed resources in vert/pixel shader");
  7853. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsHeap", nullptr, ShaderOpSet);
  7854. VerifyAtomicsTypedTest(test, 64*64+6, 64);
  7855. }
  7856. TEST_F(ExecutionTest, AtomicsShared64Test) {
  7857. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7858. CComPtr<IStream> pStream;
  7859. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7860. CComPtr<ID3D12Device> pDevice;
  7861. if (!CreateDevice(&pDevice, D3D_SHADER_MODEL_6_6))
  7862. return;
  7863. if (!DoesDeviceSupportInt64(pDevice)) {
  7864. WEX::Logging::Log::Comment(L"Device does not support int64 operations.");
  7865. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7866. return;
  7867. }
  7868. if (!DoesDeviceSupportShared64Atomics(pDevice)) {
  7869. WEX::Logging::Log::Comment(L"Device does not support int64 atomic operations on groupshared variables.");
  7870. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  7871. return;
  7872. }
  7873. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7874. std::make_shared<st::ShaderOpSet>();
  7875. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7876. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("AtomicsRoot");
  7877. // Reassign shader stages to 64-bit versions
  7878. // Collect 64-bit shaders
  7879. LPCSTR CS64 = nullptr, PS64 = nullptr;
  7880. LPCSTR AS64 = nullptr, MS64 = nullptr;
  7881. for (st::ShaderOpShader &S : pShaderOp->Shaders) {
  7882. if (!strcmp(S.Name, "CSSH64")) CS64 = S.Name;
  7883. if (!strcmp(S.Name, "CSSH64")) CS64 = S.Name;
  7884. if (!strcmp(S.Name, "PS64")) PS64 = S.Name;
  7885. if (!strcmp(S.Name, "ASSH64")) AS64 = S.Name;
  7886. if (!strcmp(S.Name, "MSSH64")) MS64 = S.Name;
  7887. }
  7888. pShaderOp->CS = CS64;
  7889. pShaderOp->PS = PS64;
  7890. pShaderOp->AS = AS64;
  7891. pShaderOp->MS = MS64;
  7892. LogCommentFmt(L"Verifying 64-bit integer atomic operations on groupshared variables in compute shader");
  7893. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsRoot", nullptr, ShaderOpSet);
  7894. VerifyAtomicsSharedTest(test, 32*32, 64);
  7895. // Test mesh shader if available
  7896. pShaderOp->CS = nullptr;
  7897. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7898. LogCommentFmt(L"Verifying 64-bit integer atomic operations on groupshared variables in amp/mesh/pixel shader");
  7899. test = RunShaderOpTestAfterParse(pDevice, m_support, "AtomicsRoot", nullptr, ShaderOpSet);
  7900. VerifyAtomicsSharedTest(test, 8*8*2 + 8*8*2, 64);
  7901. }
  7902. }
  7903. // Float Atomics
  7904. // These operations are almost the same as for the 32-bit and 64-bit integer tests
  7905. // The difference is that there is no need to verify the upper bits.
  7906. // So there is no storing of different parts in upper and lower halves.
  7907. // Additionally, the only operations that are supported on floats
  7908. // are compare and exchange operations. So that's all that is tested here.
  7909. // Just as above, a number of lanes are assigned the same output value.
  7910. // Unlike above, one location is needed for the result of the special NaN test
  7911. // For this reason, the conversion is reduced by one and shifted by one to leave
  7912. // the zero-indexed location available.
  7913. // Verify results for a particular set of atomics results
  7914. void VerifyAtomicFloatResults(const float *results) {
  7915. // The first entry is for NaN to ensure that compares between NaNs succeed
  7916. // The sentinal value is 0.123, for which this compare is sufficient.
  7917. VERIFY_IS_TRUE(results[0] >= 0.120 && results[0] < 0.125);
  7918. // Start at 1 because 0 is just for NaN tests
  7919. for (int i = 1; i < 64; i++) {
  7920. VERIFY_ARE_EQUAL((int(results[i])/3)%63 + 1, i);
  7921. }
  7922. }
  7923. void VerifyAtomicsFloatSharedTest(std::shared_ptr<ShaderOpTestResult> test) {
  7924. MappedData Data;
  7925. const float *pData = nullptr;
  7926. test->Test->GetReadBackData("U4", &Data);
  7927. pData = (float *)Data.data();
  7928. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on groupshared variables");
  7929. VerifyAtomicFloatResults(pData);
  7930. }
  7931. void VerifyAtomicsFloatTest(std::shared_ptr<ShaderOpTestResult> test) {
  7932. // struct mirroring that in the shader
  7933. struct AtomicStuff {
  7934. float prepad[2][3];
  7935. float fltEl[2];
  7936. struct useless {
  7937. uint32_t unused[3];
  7938. } postpad;
  7939. };
  7940. // Test Compute Shader
  7941. MappedData Data;
  7942. const float *pData = nullptr;
  7943. test->Test->GetReadBackData("U0", &Data);
  7944. const AtomicStuff *pStructData = (AtomicStuff *)Data.data();
  7945. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWStructuredBuffer resources");
  7946. VERIFY_IS_TRUE(pStructData[0].fltEl[1] >= 0.120 && pStructData[0].fltEl[1] < 0.125);
  7947. for (int i = 1; i < 64; i++) {
  7948. VERIFY_ARE_EQUAL((int(pStructData[i].fltEl[1])/3)%63 + 1, i);
  7949. }
  7950. test->Test->GetReadBackData("U1", &Data);
  7951. pData = (float *)Data.data();
  7952. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWByteAddressBuffer resources");
  7953. VerifyAtomicFloatResults(pData);
  7954. test->Test->GetReadBackData("U2", &Data);
  7955. pData = (float *)Data.data();
  7956. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWBuffer resources");
  7957. VerifyAtomicFloatResults(pData);
  7958. test->Test->GetReadBackData("U3", &Data);
  7959. pData = (float *)Data.data();
  7960. LogCommentFmt(L"Verifying float cmp/xchg atomic operations on RWTexture resources");
  7961. VerifyAtomicFloatResults(pData);
  7962. }
  7963. TEST_F(ExecutionTest, AtomicsFloatTest) {
  7964. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  7965. CComPtr<IStream> pStream;
  7966. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  7967. CComPtr<ID3D12Device> pDevice;
  7968. if (!CreateDevice(&pDevice))
  7969. return;
  7970. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  7971. std::make_shared<st::ShaderOpSet>();
  7972. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  7973. st::ShaderOp *pShaderOp = ShaderOpSet->GetShaderOp("FloatAtomics");
  7974. // Test compute shader
  7975. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in compute shader");
  7976. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7977. VerifyAtomicsFloatTest(test);
  7978. VerifyAtomicsFloatSharedTest(test);
  7979. // Test mesh shader if available
  7980. pShaderOp->CS = nullptr;
  7981. if (DoesDeviceSupportMeshShaders(pDevice)) {
  7982. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in amp/mesh/pixel shaders");
  7983. test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7984. VerifyAtomicsFloatTest(test);
  7985. VerifyAtomicsFloatSharedTest(test);
  7986. }
  7987. // Test Vertex + Pixel shader
  7988. pShaderOp->MS = nullptr;
  7989. LogCommentFmt(L"Verifying float cmp/xchg atomic operations in vert/pixel shaders");
  7990. test = RunShaderOpTestAfterParse(pDevice, m_support, "FloatAtomics", nullptr, ShaderOpSet);
  7991. VerifyAtomicsFloatTest(test);
  7992. }
  7993. // The IsHelperLane test renders 3-pixel triangle into 16x16 render target restricted
  7994. // to 2x2 viewport alligned at (0,0) which guarantees it will run in a single quad.
  7995. //
  7996. // Pixels to be rendered*
  7997. // (0,0)* (0,1)*
  7998. // (1,0) (1,1)*
  7999. //
  8000. // Pixel (1,0) is not rendered and is in helper lane.
  8001. //
  8002. // Each thread will use ddx_fine and ddy_fine to read the IsHelperLane() values from other threads.
  8003. // The bottom right pixel will write the results into the UAV buffer.
  8004. //
  8005. // Then the top level pixel (0,0) is discarded and the process above is repeated.
  8006. //
  8007. // Runs with shader models 6.0 and 6.6 to test both the HLSL built-in IsHelperLane fallback
  8008. // function (sm <= 6.5) and the IsHelperLane intrisics (sm >= 6.6).
  8009. //
  8010. TEST_F(ExecutionTest, HelperLaneTest) {
  8011. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  8012. CComPtr<IStream> pStream;
  8013. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  8014. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  8015. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  8016. #ifdef ISHELPERLANE_PLACEHOLDER
  8017. string args = "-DISHELPERLANE_PLACEHOLDER";
  8018. #else
  8019. string args = "";
  8020. #endif
  8021. D3D_SHADER_MODEL TestShaderModels[] = { D3D_SHADER_MODEL_6_0, D3D_SHADER_MODEL_6_6 };
  8022. for (unsigned i = 0; i < _countof(TestShaderModels); i++) {
  8023. D3D_SHADER_MODEL sm = TestShaderModels[i];
  8024. LogCommentFmt(L"Verifying IsHelperLane in shader model 6.%1u", ((UINT)sm & 0x0f));
  8025. CComPtr<ID3D12Device> pDevice;
  8026. if (!CreateDevice(&pDevice, sm, false /* skipUnsupported */))
  8027. continue;
  8028. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestNoWave",
  8029. // this callbacked is called when the test is creating the resource to run the test
  8030. [&](LPCSTR Name, std::vector<BYTE>& Data, st::ShaderOp* pShaderOp) {
  8031. VERIFY_IS_TRUE(0 == _stricmp(Name, "UAVBuffer0"));
  8032. std::fill(Data.begin(), Data.end(), (BYTE)0xCC);
  8033. pShaderOp->Shaders.at(0).Arguments = args.c_str();
  8034. pShaderOp->Shaders.at(1).Arguments = args.c_str();
  8035. }, ShaderOpSet);
  8036. struct HelperLaneTestResult {
  8037. int32_t is_helper_00;
  8038. int32_t is_helper_10;
  8039. int32_t is_helper_01;
  8040. int32_t is_helper_11;
  8041. };
  8042. MappedData uavData;
  8043. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  8044. HelperLaneTestResult* pTestResults = (HelperLaneTestResult*)uavData.data();
  8045. MappedData renderData;
  8046. test->Test->GetReadBackData("RTarget", &renderData);
  8047. const uint32_t* pPixels = (uint32_t*)renderData.data();
  8048. // before discard
  8049. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_00, 0);
  8050. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_10, 0);
  8051. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_01, 1);
  8052. VERIFY_ARE_EQUAL(pTestResults[0].is_helper_11, 0);
  8053. // after discard
  8054. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_00, 1);
  8055. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_10, 0);
  8056. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_01, 1);
  8057. VERIFY_ARE_EQUAL(pTestResults[1].is_helper_11, 0);
  8058. UNREFERENCED_PARAMETER(pPixels);
  8059. }
  8060. }
  8061. struct HelperLaneWaveTestResult60 {
  8062. // 6.0 wave ops
  8063. int32_t anyTrue;
  8064. int32_t allTrue;
  8065. XMUINT4 ballot;
  8066. int32_t waterfallLoopCount;
  8067. int32_t allEqual;
  8068. int32_t countBits;
  8069. int32_t sum;
  8070. int32_t product;
  8071. int32_t bitAnd;
  8072. int32_t bitOr;
  8073. int32_t bitXor;
  8074. int32_t min;
  8075. int32_t max;
  8076. int32_t prefixCountBits;
  8077. int32_t prefixProduct;
  8078. int32_t prefixSum;
  8079. };
  8080. struct HelperLaneQuadTestResult {
  8081. int32_t is_helper_this;
  8082. int32_t is_helper_across_X;
  8083. int32_t is_helper_across_Y;
  8084. int32_t is_helper_across_Diag;
  8085. };
  8086. struct HelperLaneWaveTestResult65 {
  8087. // 6.5 wave ops
  8088. XMUINT4 match;
  8089. int32_t mpCountBits;
  8090. int32_t mpSum;
  8091. int32_t mpProduct;
  8092. int32_t mpBitAnd;
  8093. int32_t mpBitOr;
  8094. int32_t mpBitXor;
  8095. };
  8096. struct HelperLaneWaveTestResult {
  8097. HelperLaneWaveTestResult60 sm60;
  8098. HelperLaneQuadTestResult sm60_quad;
  8099. HelperLaneWaveTestResult65 sm65;
  8100. };
  8101. struct foo { int32_t a; int32_t b; int32_t c; };
  8102. struct bar { foo f; int32_t d; XMUINT4 g; };
  8103. foo f = {1, 2, 3};
  8104. bar b = { { 1, 2, 3 }, 0, { 1, 2, 3, 4 } };
  8105. HelperLaneWaveTestResult HelperLane_CS_ExpectedResults = {
  8106. // HelperLaneWaveTestResult60
  8107. { 0, 1, { 0x7, 0, 0, 0 }, 3, 1, 3, 12, 64, 1, 0, 0, 10, 1, 2, 16, 4 },
  8108. // HelperLaneQuadTestResult
  8109. { 0, 0, 0, 0 },
  8110. // HelperLaneWaveTestResult65
  8111. { {0x7, 0, 0, 0}, 2, 4, 16, 1, 0, 0 }
  8112. };
  8113. HelperLaneWaveTestResult HelperLane_VS_ExpectedResults = HelperLane_CS_ExpectedResults;
  8114. HelperLaneWaveTestResult HelperLane_PS_ExpectedResults = {
  8115. // HelperLaneWaveTestResult60
  8116. { 0, 1, { 0xB, 0, 0, 0 }, 3, 1, 3, 12, 64, 1, 0, 0, 10, 1, 2, 16, 4 },
  8117. // HelperLaneQuadTestResult
  8118. { 0, 1, 0, 0 },
  8119. // HelperLaneWaveTestResult65
  8120. { {0xB, 0, 0, 0}, 2, 4, 16, 1, 0, 0 }
  8121. };
  8122. HelperLaneWaveTestResult HelperLane_PSAfterDiscard_ExpectedResults = {
  8123. // HelperLaneWaveTestResult60
  8124. { 0, 1, { 0xA, 0, 0, 0 }, 2, 1, 2, 8, 16, 1, 0, 0, 10, 1, 1, 4, 2 },
  8125. // HelperLaneQuadTestResult
  8126. { 0, 1, 0, 1 },
  8127. // HelperLaneWaveTestResult65
  8128. { {0xA, 0, 0, 0}, 1, 2, 4, 1, 0, 0 }
  8129. };
  8130. bool HelperLaneResultLogAndVerify(const wchar_t* testDesc, uint32_t expectedValue, uint32_t actualValue) {
  8131. bool matches = (expectedValue == actualValue);
  8132. LogCommentFmt(L"%s%s, expected = %u, actual = %u", matches ? L" - " : L"FAILED: ", testDesc, expectedValue, actualValue);
  8133. return matches;
  8134. }
  8135. bool HelperLaneResultLogAndVerify(const wchar_t* testDesc, XMUINT4 expectedValue, XMUINT4 actualValue) {
  8136. bool matches = (expectedValue.x == actualValue.x && expectedValue.y == actualValue.y &&
  8137. expectedValue.z == actualValue.z && expectedValue.w == actualValue.w);
  8138. LogCommentFmt(L"%s%s, expected = (0x%X,0x%X,0x%X,0x%X), actual = (0x%X,0x%X,0x%X,0x%X)", matches ? L" - " : L"FAILED: ", testDesc,
  8139. expectedValue.x, expectedValue.y, expectedValue.z, expectedValue.w, actualValue.x, actualValue.y, actualValue.z, actualValue.w);
  8140. return matches;
  8141. }
  8142. bool VerifyHelperLaneWaveResults(ExecutionTest::D3D_SHADER_MODEL sm, HelperLaneWaveTestResult& testResults, HelperLaneWaveTestResult& expectedResults, bool verifyQuads) {
  8143. bool passed = true;
  8144. {
  8145. HelperLaneWaveTestResult60& tr60 = testResults.sm60;
  8146. HelperLaneWaveTestResult60& tr60exp = expectedResults.sm60;
  8147. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAnyTrue(IsHelperLane())", tr60exp.anyTrue, tr60.anyTrue);
  8148. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAllTrue(!IsHelperLane())", tr60exp.allTrue, tr60.allTrue);
  8149. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBallot(true) has exactly 3 bits set", tr60exp.ballot, tr60.ballot);
  8150. passed &= HelperLaneResultLogAndVerify(L"!WaveReadLaneFirst(IsHelperLane()) && WaveIsFirstLane() in a waterfall loop", tr60exp.waterfallLoopCount, tr60.waterfallLoopCount);
  8151. passed &= HelperLaneResultLogAndVerify(L"WaveActiveAllEqual(IsHelperLane())", tr60exp.allEqual, tr60.allEqual);
  8152. passed &= HelperLaneResultLogAndVerify(L"WaveActiveCountBits(true)", tr60exp.countBits, tr60.countBits);
  8153. passed &= HelperLaneResultLogAndVerify(L"WaveActiveSum(4)", tr60exp.sum, tr60.sum);
  8154. passed &= HelperLaneResultLogAndVerify(L"WaveActiveProduct(4)", tr60exp.product, tr60.product);
  8155. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitAnd(!IsHelperLane())", tr60exp.bitAnd, tr60.bitAnd);
  8156. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitOr(IsHelperLane())", tr60exp.bitOr, tr60.bitOr);
  8157. passed &= HelperLaneResultLogAndVerify(L"WaveActiveBitXor(IsHelperLane())", tr60exp.bitXor, tr60.bitXor);
  8158. passed &= HelperLaneResultLogAndVerify(L"WaveActiveMin(IsHelperLane() ? 1 : 10)", tr60exp.min, tr60.min);
  8159. passed &= HelperLaneResultLogAndVerify(L"WaveActiveMax(IsHelperLane() ? 10 : 1)", tr60exp.max, tr60.max);
  8160. passed &= HelperLaneResultLogAndVerify(L"WavePrefixCountBits(1)", tr60exp.prefixCountBits, tr60.prefixCountBits);
  8161. passed &= HelperLaneResultLogAndVerify(L"WavePrefixProduct(4)", tr60exp.prefixProduct, tr60.prefixProduct);
  8162. passed &= HelperLaneResultLogAndVerify(L"WavePrefixSum(2)", tr60exp.prefixSum, tr60.prefixSum);
  8163. }
  8164. if (verifyQuads) {
  8165. HelperLaneQuadTestResult& quad_tr = testResults.sm60_quad;
  8166. HelperLaneQuadTestResult& quad_tr_exp = expectedResults.sm60_quad;
  8167. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 3 / pixel (1,1) - IsHelperLane()", quad_tr_exp.is_helper_this, quad_tr.is_helper_this);
  8168. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 2 / pixel (0,1) - IsHelperLane()", quad_tr_exp.is_helper_across_X, quad_tr.is_helper_across_X);
  8169. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 1 / pixel (1,0) - IsHelperLane()", quad_tr_exp.is_helper_across_Y, quad_tr.is_helper_across_Y);
  8170. passed &= HelperLaneResultLogAndVerify(L"QuadReadAcross* - lane 0 / pixel (0,0) - IsHelperLane()", quad_tr_exp.is_helper_across_Diag, quad_tr.is_helper_across_Diag);
  8171. }
  8172. if (sm >= D3D_SHADER_MODEL_6_5) {
  8173. HelperLaneWaveTestResult65& tr65 = testResults.sm65;
  8174. HelperLaneWaveTestResult65& tr65exp = expectedResults.sm65;
  8175. passed &= HelperLaneResultLogAndVerify(L"WaveMatch(true) has exactly 3 bits set", tr65exp.match, tr65.match);
  8176. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixCountBits(1, no_masked_bits)", tr65exp.mpCountBits, tr65.mpCountBits);
  8177. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixSum(2, no_masked_bits)", tr65exp.mpSum, tr65.mpSum);
  8178. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixProduct(4, no_masked_bits)", tr65exp.mpProduct, tr65.mpProduct);
  8179. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixAnd(IsHelperLane() ? 0 : 1, no_masked_bits)", tr65exp.mpBitAnd, tr65.mpBitAnd);
  8180. passed &= HelperLaneResultLogAndVerify(L"WaveMultiPrefixOr(IsHelperLane() ? 1 : 0, no_masked_bits)", tr65exp.mpBitOr, tr65.mpBitOr);
  8181. passed &= HelperLaneResultLogAndVerify(L"verify WaveMultiPrefixXor(IsHelperLane() ? 1 : 0, no_masked_bits)", tr65exp.mpBitXor, tr65.mpBitXor);
  8182. }
  8183. return passed;
  8184. }
  8185. void CleanUAVBuffer0Buffer(LPCSTR BufferName, std::vector<BYTE>& Data, st::ShaderOp* pShaderOp) {
  8186. UNREFERENCED_PARAMETER(pShaderOp);
  8187. VERIFY_IS_TRUE(0 == _stricmp(BufferName, "UAVBuffer0"));
  8188. std::fill(Data.begin(), Data.end(), (BYTE)0xCC);
  8189. }
  8190. //
  8191. // The IsHelperLane test that use Wave intrinsics to verify IsHelperLane() and Wave operations on active lanes.
  8192. //
  8193. // Runs with shader models 6.0, 6.5 and 6.6 to test both the HLSL built-in IsHelperLane fallback
  8194. // function (sm <= 6.5) and the IsHelperLane intrisics (sm >= 6.6) and the shader model 6.5 wave intrinsics (sm >= 6.5).
  8195. //
  8196. // For compute and vertex shaders IsHelperLane() always returns false and might be optimized away in the front end.
  8197. // However it can be exposed to the driver in CS/VS through an exported function in a library so drivers need
  8198. // to be prepared to handle it. For this reason the test is compiled with disabled optimizations (/Od).
  8199. // The tests are also validating that wave intrinsics operate correctly with 3 threads in a CS or 3 vertices
  8200. // in a VS where the rest of the lanes in the wave are not active (dead lanes).
  8201. //
  8202. TEST_F(ExecutionTest, HelperLaneTestWave) {
  8203. WEX::TestExecution::SetVerifyOutput verifySettings(WEX::TestExecution::VerifyOutputSettings::LogOnlyFailures);
  8204. CComPtr<IStream> pStream;
  8205. ReadHlslDataIntoNewStream(L"ShaderOpArith.xml", &pStream);
  8206. std::shared_ptr<st::ShaderOpSet> ShaderOpSet = std::make_shared<st::ShaderOpSet>();
  8207. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  8208. st::ShaderOp* pShaderOp = ShaderOpSet->GetShaderOp("HelperLaneTestWave");
  8209. #ifdef ISHELPERLANE_PLACEHOLDER
  8210. LPCSTR args = "/Od -DISHELPERLANE_PLACEHOLDER";
  8211. #else
  8212. LPCSTR args = "/Od";
  8213. #endif
  8214. if (args[0]) {
  8215. for (st::ShaderOpShader& S : pShaderOp->Shaders)
  8216. S.Arguments = args;
  8217. }
  8218. bool testPassed = true;
  8219. D3D_SHADER_MODEL TestShaderModels[] = { D3D_SHADER_MODEL_6_0, D3D_SHADER_MODEL_6_5, D3D_SHADER_MODEL_6_6 };
  8220. for (unsigned i = 0; i < _countof(TestShaderModels); i++) {
  8221. D3D_SHADER_MODEL sm = TestShaderModels[i];
  8222. LogCommentFmt(L"\r\nVerifying IsHelperLane using Wave intrinsics in shader model 6.%1u", ((UINT)sm & 0x0f));
  8223. bool smPassed = true;
  8224. CComPtr<ID3D12Device> pDevice;
  8225. if (!CreateDevice(&pDevice, sm, false /* skipUnsupported */)) {
  8226. continue;
  8227. }
  8228. if (GetTestParamUseWARP(UseWarpByDefault()) || IsDeviceBasicAdapter(pDevice)) {
  8229. WEX::Logging::Log::Comment(L"WARP has a known issue with HelperLaneTestWave.");
  8230. WEX::Logging::Log::Result(WEX::Logging::TestResults::Skipped);
  8231. return;
  8232. }
  8233. if (!DoesDeviceSupportWaveOps(pDevice)) {
  8234. LogCommentFmt(L"Device does not support wave operations in shader model 6.%1u", ((UINT)sm & 0x0f));
  8235. continue;
  8236. }
  8237. if (sm == D3D_SHADER_MODEL_6_5) {
  8238. // Reassign shader stages to 6.5 versions
  8239. LPCSTR CS65 = nullptr, VS65 = nullptr, PS65 = nullptr;
  8240. for (st::ShaderOpShader& S : pShaderOp->Shaders) {
  8241. if (!strcmp(S.Name, "CS65")) CS65 = S.Name;
  8242. if (!strcmp(S.Name, "VS65")) VS65 = S.Name;
  8243. if (!strcmp(S.Name, "PS65")) PS65 = S.Name;
  8244. }
  8245. pShaderOp->CS = CS65;
  8246. pShaderOp->VS = VS65;
  8247. pShaderOp->PS = PS65;
  8248. } else if (sm == D3D_SHADER_MODEL_6_6) {
  8249. // Reassign shader stages to 6.6 versions
  8250. LPCSTR CS66 = nullptr, VS66 = nullptr, PS66 = nullptr;
  8251. for (st::ShaderOpShader& S : pShaderOp->Shaders) {
  8252. if (!strcmp(S.Name, "CS66")) CS66 = S.Name;
  8253. if (!strcmp(S.Name, "VS66")) VS66 = S.Name;
  8254. if (!strcmp(S.Name, "PS66")) PS66 = S.Name;
  8255. }
  8256. pShaderOp->CS = CS66;
  8257. pShaderOp->VS = VS66;
  8258. pShaderOp->PS = PS66;
  8259. }
  8260. const unsigned CS_INDEX = 0, VS_INDEX = 0, PS_INDEX = 1, PS_INDEX_AFTER_DISCARD = 2;
  8261. // Test Compute shader
  8262. {
  8263. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestWave",
  8264. CleanUAVBuffer0Buffer, ShaderOpSet);
  8265. MappedData uavData;
  8266. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  8267. HelperLaneWaveTestResult* pTestResults = (HelperLaneWaveTestResult*)uavData.data();
  8268. LogCommentFmt(L"\r\nCompute shader");
  8269. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[CS_INDEX], HelperLane_CS_ExpectedResults, true);
  8270. }
  8271. // Test Vertex + Pixel shader
  8272. {
  8273. pShaderOp->CS = nullptr;
  8274. std::shared_ptr<ShaderOpTestResult> test = RunShaderOpTestAfterParse(pDevice, m_support, "HelperLaneTestWave", CleanUAVBuffer0Buffer, ShaderOpSet);
  8275. MappedData uavData;
  8276. test->Test->GetReadBackData("UAVBuffer0", &uavData);
  8277. HelperLaneWaveTestResult* pTestResults = (HelperLaneWaveTestResult*)uavData.data();
  8278. LogCommentFmt(L"\r\nVertex shader");
  8279. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[VS_INDEX], HelperLane_VS_ExpectedResults, false);
  8280. LogCommentFmt(L"\r\nPixel shader");
  8281. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[PS_INDEX], HelperLane_PS_ExpectedResults, true);
  8282. LogCommentFmt(L"\r\nPixel shader with discarded pixel");
  8283. smPassed &= VerifyHelperLaneWaveResults(sm, pTestResults[PS_INDEX_AFTER_DISCARD], HelperLane_PSAfterDiscard_ExpectedResults, true);
  8284. MappedData renderData;
  8285. test->Test->GetReadBackData("RTarget", &renderData);
  8286. const uint32_t* pPixels = (uint32_t*)renderData.data();
  8287. UNREFERENCED_PARAMETER(pPixels);
  8288. }
  8289. testPassed &= smPassed;
  8290. }
  8291. VERIFY_ARE_EQUAL(testPassed, true);
  8292. }
  8293. #ifndef _HLK_CONF
  8294. static void WriteReadBackDump(st::ShaderOp *pShaderOp, st::ShaderOpTest *pTest,
  8295. char **pReadBackDump) {
  8296. std::stringstream str;
  8297. unsigned count = 0;
  8298. for (auto &R : pShaderOp->Resources) {
  8299. if (!R.ReadBack)
  8300. continue;
  8301. ++count;
  8302. str << "Resource: " << R.Name << "\r\n";
  8303. // Find a descriptor that can tell us how to dump this resource.
  8304. bool found = false;
  8305. for (auto &Heaps : pShaderOp->DescriptorHeaps) {
  8306. for (auto &D : Heaps.Descriptors) {
  8307. if (_stricmp(D.ResName, R.Name) != 0) {
  8308. continue;
  8309. }
  8310. found = true;
  8311. if (_stricmp(D.Kind, "UAV") != 0) {
  8312. str << "Resource dump for kind " << D.Kind << " not implemented yet.\r\n";
  8313. break;
  8314. }
  8315. if (D.UavDesc.ViewDimension != D3D12_UAV_DIMENSION_BUFFER) {
  8316. str << "Resource dump for this kind of view dimension not implemented yet.\r\n";
  8317. break;
  8318. }
  8319. // We can map back to the structure if a structured buffer via the shader, but
  8320. // we'll keep this simple and simply dump out 32-bit uint/float representations.
  8321. MappedData data;
  8322. pTest->GetReadBackData(R.Name, &data);
  8323. uint32_t *pData = (uint32_t *)data.data();
  8324. size_t u32_count = ((size_t)R.Desc.Width) / sizeof(uint32_t);
  8325. for (size_t i = 0; i < u32_count; ++i) {
  8326. float f = *(float *)pData;
  8327. str << i << ": 0n" << *pData << " 0x" << std::hex << *pData
  8328. << std::dec << " " << f << "\r\n";
  8329. ++pData;
  8330. }
  8331. break;
  8332. }
  8333. if (found) break;
  8334. }
  8335. if (!found) {
  8336. str << "Unable to find a view for the resource.\r\n";
  8337. }
  8338. }
  8339. str << "Resources read back: " << count << "\r\n";
  8340. std::string s(str.str());
  8341. CComHeapPtr<char> pDump;
  8342. if (!pDump.Allocate(s.size() + 1))
  8343. throw std::bad_alloc();
  8344. memcpy(pDump.m_pData, s.data(), s.size());
  8345. pDump.m_pData[s.size()] = '\0';
  8346. *pReadBackDump = pDump.Detach();
  8347. }
  8348. // This is the exported interface by use from HLSLHost.exe.
  8349. // It's exclusive with the use of the DLL as a TAEF target.
  8350. extern "C" {
  8351. __declspec(dllexport) HRESULT WINAPI InitializeOpTests(void *pStrCtx, st::OutputStringFn pOutputStrFn) {
  8352. HRESULT hr = ExecutionTest::EnableExperimentalShaderModels();
  8353. if (FAILED(hr)) {
  8354. pOutputStrFn(pStrCtx, L"Unable to enable experimental shader models.\r\n.");
  8355. }
  8356. return S_OK;
  8357. }
  8358. __declspec(dllexport) HRESULT WINAPI
  8359. RunOpTest(void *pStrCtx, st::OutputStringFn pOutputStrFn, LPCSTR pText,
  8360. ID3D12Device *pDevice, ID3D12CommandQueue *pCommandQueue,
  8361. ID3D12Resource *pRenderTarget, char **pReadBackDump) {
  8362. HRESULT hr;
  8363. if (pReadBackDump) *pReadBackDump = nullptr;
  8364. st::SetOutputFn(pStrCtx, pOutputStrFn);
  8365. CComPtr<ID3D12InfoQueue> pInfoQueue;
  8366. CComHeapPtr<char> pDump;
  8367. bool FilterCreation = false;
  8368. if (SUCCEEDED(pDevice->QueryInterface(&pInfoQueue))) {
  8369. // Creation is largely driven by inputs, so don't log create/destroy messages.
  8370. pInfoQueue->PushEmptyStorageFilter();
  8371. pInfoQueue->PushEmptyRetrievalFilter();
  8372. if (FilterCreation) {
  8373. D3D12_INFO_QUEUE_FILTER filter;
  8374. D3D12_MESSAGE_CATEGORY denyCategories[] = { D3D12_MESSAGE_CATEGORY_STATE_CREATION };
  8375. ZeroMemory(&filter, sizeof(filter));
  8376. filter.DenyList.NumCategories = _countof(denyCategories);
  8377. filter.DenyList.pCategoryList = denyCategories;
  8378. pInfoQueue->PushStorageFilter(&filter);
  8379. }
  8380. }
  8381. else {
  8382. pOutputStrFn(pStrCtx, L"Unable to enable info queue for D3D.\r\n.");
  8383. }
  8384. try {
  8385. dxc::DxcDllSupport m_support;
  8386. m_support.Initialize();
  8387. const char *pName = nullptr;
  8388. CComPtr<IStream> pStream = SHCreateMemStream((BYTE *)pText, (UINT)strlen(pText));
  8389. std::shared_ptr<st::ShaderOpSet> ShaderOpSet =
  8390. std::make_shared<st::ShaderOpSet>();
  8391. st::ParseShaderOpSetFromStream(pStream, ShaderOpSet.get());
  8392. st::ShaderOp *pShaderOp;
  8393. if (pName == nullptr) {
  8394. if (ShaderOpSet->ShaderOps.size() != 1) {
  8395. pOutputStrFn(pStrCtx, L"Expected a single shader operation.\r\n");
  8396. return E_FAIL;
  8397. }
  8398. pShaderOp = ShaderOpSet->ShaderOps[0].get();
  8399. }
  8400. else {
  8401. pShaderOp = ShaderOpSet->GetShaderOp(pName);
  8402. }
  8403. if (pShaderOp == nullptr) {
  8404. std::string msg = "Unable to find shader op ";
  8405. msg += pName;
  8406. msg += "; available ops";
  8407. const char sep = ':';
  8408. for (auto &pAvailOp : ShaderOpSet->ShaderOps) {
  8409. msg += sep;
  8410. msg += pAvailOp->Name ? pAvailOp->Name : "[n/a]";
  8411. }
  8412. CA2W msgWide(msg.c_str());
  8413. pOutputStrFn(pStrCtx, msgWide);
  8414. return E_FAIL;
  8415. }
  8416. std::shared_ptr<st::ShaderOpTest> test = std::make_shared<st::ShaderOpTest>();
  8417. test->SetupRenderTarget(pShaderOp, pDevice, pCommandQueue, pRenderTarget);
  8418. test->SetDxcSupport(&m_support);
  8419. test->RunShaderOp(pShaderOp);
  8420. test->PresentRenderTarget(pShaderOp, pCommandQueue, pRenderTarget);
  8421. pOutputStrFn(pStrCtx, L"Rendering complete.\r\n");
  8422. if (!pShaderOp->IsCompute()) {
  8423. D3D12_QUERY_DATA_PIPELINE_STATISTICS stats;
  8424. test->GetPipelineStats(&stats);
  8425. wchar_t statsText[400];
  8426. StringCchPrintfW(statsText, _countof(statsText),
  8427. L"Vertices/primitives read by input assembler: %I64u/%I64u\r\n"
  8428. L"Vertex shader invocations: %I64u\r\n"
  8429. L"Geometry shader invocations/output primitive: %I64u/%I64u\r\n"
  8430. L"Primitives sent to rasterizer/rendered: %I64u/%I64u\r\n"
  8431. L"PS/HS/DS/CS invocations: %I64u/%I64u/%I64u/%I64u\r\n",
  8432. stats.IAVertices, stats.IAPrimitives, stats.VSInvocations,
  8433. stats.GSInvocations, stats.GSPrimitives, stats.CInvocations,
  8434. stats.CPrimitives, stats.PSInvocations, stats.HSInvocations,
  8435. stats.DSInvocations, stats.CSInvocations);
  8436. pOutputStrFn(pStrCtx, statsText);
  8437. }
  8438. if (pReadBackDump) {
  8439. WriteReadBackDump(pShaderOp, test.get(), &pDump);
  8440. }
  8441. hr = S_OK;
  8442. }
  8443. catch (const CAtlException &E)
  8444. {
  8445. hr = E.m_hr;
  8446. }
  8447. catch (const std::bad_alloc &)
  8448. {
  8449. hr = E_OUTOFMEMORY;
  8450. }
  8451. catch (const std::exception &)
  8452. {
  8453. hr = E_FAIL;
  8454. }
  8455. // Drain the device message queue if available.
  8456. if (pInfoQueue != nullptr) {
  8457. wchar_t buf[200];
  8458. StringCchPrintfW(buf, _countof(buf),
  8459. L"NumStoredMessages=%u limit/discarded by limit=%u/%u "
  8460. L"allowed/denied by storage filter=%u/%u "
  8461. L"NumStoredMessagesAllowedByRetrievalFilter=%u\r\n",
  8462. (unsigned)pInfoQueue->GetNumStoredMessages(),
  8463. (unsigned)pInfoQueue->GetMessageCountLimit(),
  8464. (unsigned)pInfoQueue->GetNumMessagesDiscardedByMessageCountLimit(),
  8465. (unsigned)pInfoQueue->GetNumMessagesAllowedByStorageFilter(),
  8466. (unsigned)pInfoQueue->GetNumMessagesDeniedByStorageFilter(),
  8467. (unsigned)pInfoQueue->GetNumStoredMessagesAllowedByRetrievalFilter());
  8468. pOutputStrFn(pStrCtx, buf);
  8469. WriteInfoQueueMessages(pStrCtx, pOutputStrFn, pInfoQueue);
  8470. pInfoQueue->ClearStoredMessages();
  8471. pInfoQueue->PopRetrievalFilter();
  8472. pInfoQueue->PopStorageFilter();
  8473. if (FilterCreation) {
  8474. pInfoQueue->PopStorageFilter();
  8475. }
  8476. }
  8477. if (pReadBackDump) *pReadBackDump = pDump.Detach();
  8478. return hr;
  8479. }
  8480. }
  8481. #endif
  8482. // MARKER: ExecutionTest/DxilConf Shared Implementation End
  8483. // Do not remove the line above - it is used by TranslateExecutionTest.py