DxilValidation.cpp 246 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilValidation.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. // This file provides support for validating DXIL shaders. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "dxc/Support/Global.h"
  12. #include "dxc/Support/WinIncludes.h"
  13. #include "dxc/Support/FileIOHelper.h"
  14. #include "dxc/HLSL/DxilValidation.h"
  15. #include "dxc/DxilContainer/DxilContainerAssembler.h"
  16. #include "dxc/DxilContainer/DxilRuntimeReflection.h"
  17. #include "dxc/HLSL/DxilGenerationPass.h"
  18. #include "dxc/DXIL/DxilOperations.h"
  19. #include "dxc/DXIL/DxilModule.h"
  20. #include "dxc/DXIL/DxilShaderModel.h"
  21. #include "dxc/DxilContainer/DxilContainer.h"
  22. #include "dxc/DXIL/DxilFunctionProps.h"
  23. #include "dxc/DXIL/DxilUtil.h"
  24. #include "dxc/DXIL/DxilInstructions.h"
  25. #include "llvm/Analysis/ReducibilityAnalysis.h"
  26. #include "dxc/DXIL/DxilEntryProps.h"
  27. #include "dxc/DXIL/DxilResourceProperties.h"
  28. #include "llvm/ADT/ArrayRef.h"
  29. #include "llvm/Analysis/CallGraph.h"
  30. #include "llvm/IR/LLVMContext.h"
  31. #include "llvm/IR/Module.h"
  32. #include "llvm/IR/Type.h"
  33. #include "llvm/IR/Operator.h"
  34. #include "llvm/IR/Instructions.h"
  35. #include "llvm/IR/InstIterator.h"
  36. #include "llvm/IR/Constants.h"
  37. #include "llvm/IR/DiagnosticInfo.h"
  38. #include "llvm/IR/DiagnosticPrinter.h"
  39. #include "llvm/IR/Verifier.h"
  40. #include "llvm/IR/ModuleSlotTracker.h"
  41. #include "llvm/ADT/BitVector.h"
  42. #include "llvm/Support/raw_ostream.h"
  43. #include "llvm/Support/MemoryBuffer.h"
  44. #include "llvm/Bitcode/ReaderWriter.h"
  45. #include <unordered_set>
  46. #include "llvm/Analysis/LoopInfo.h"
  47. #include "llvm/IR/Dominators.h"
  48. #include "llvm/Analysis/PostDominators.h"
  49. #include "dxc/HLSL/DxilSpanAllocator.h"
  50. #include "dxc/HLSL/DxilSignatureAllocator.h"
  51. #include "dxc/HLSL/DxilPackSignatureElement.h"
  52. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  53. #include <algorithm>
  54. #include <deque>
  55. using namespace llvm;
  56. using namespace std;
  57. ///////////////////////////////////////////////////////////////////////////////
  58. // Error messages.
  59. const char *hlsl::GetValidationRuleText(ValidationRule value) {
  60. /* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_valrule_text()</py>*/
  61. // VALRULE-TEXT:BEGIN
  62. switch(value) {
  63. case hlsl::ValidationRule::BitcodeValid: return "Module bitcode is invalid";
  64. case hlsl::ValidationRule::ContainerPartMatches: return "Container part '%0' does not match expected for module.";
  65. case hlsl::ValidationRule::ContainerPartRepeated: return "More than one container part '%0'.";
  66. case hlsl::ValidationRule::ContainerPartMissing: return "Missing part '%0' required by module.";
  67. case hlsl::ValidationRule::ContainerPartInvalid: return "Unknown part '%0' found in DXIL container.";
  68. case hlsl::ValidationRule::ContainerRootSignatureIncompatible: return "Root Signature in DXIL container is not compatible with shader.";
  69. case hlsl::ValidationRule::MetaRequired: return "TODO - Required metadata missing";
  70. case hlsl::ValidationRule::MetaKnown: return "Named metadata '%0' is unknown";
  71. case hlsl::ValidationRule::MetaUsed: return "All metadata must be used by dxil";
  72. case hlsl::ValidationRule::MetaTarget: return "Unknown target triple '%0'";
  73. case hlsl::ValidationRule::MetaWellFormed: return "TODO - Metadata must be well-formed in operand count and types";
  74. case hlsl::ValidationRule::MetaSemanticLen: return "Semantic length must be at least 1 and at most 64";
  75. case hlsl::ValidationRule::MetaInterpModeValid: return "Invalid interpolation mode for '%0'";
  76. case hlsl::ValidationRule::MetaSemaKindValid: return "Semantic kind for '%0' is invalid";
  77. case hlsl::ValidationRule::MetaNoSemanticOverlap: return "Semantic '%0' overlap at %1";
  78. case hlsl::ValidationRule::MetaSemaKindMatchesName: return "Semantic name %0 does not match System Value kind %1";
  79. case hlsl::ValidationRule::MetaDuplicateSysValue: return "System value %0 appears more than once in the same signature.";
  80. case hlsl::ValidationRule::MetaSemanticIndexMax: return "%0 semantic index exceeds maximum (%1)";
  81. case hlsl::ValidationRule::MetaSystemValueRows: return "rows for system value semantic %0 must be 1";
  82. case hlsl::ValidationRule::MetaSemanticShouldBeAllocated: return "%0 Semantic '%1' should have a valid packing location";
  83. case hlsl::ValidationRule::MetaSemanticShouldNotBeAllocated: return "%0 Semantic '%1' should have a packing location of -1";
  84. case hlsl::ValidationRule::MetaValueRange: return "Metadata value must be within range";
  85. case hlsl::ValidationRule::MetaFlagsUsage: return "Flags must match usage";
  86. case hlsl::ValidationRule::MetaDenseResIDs: return "Resource identifiers must be zero-based and dense";
  87. case hlsl::ValidationRule::MetaSignatureOverlap: return "signature element %0 at location (%1,%2) size (%3,%4) overlaps another signature element.";
  88. case hlsl::ValidationRule::MetaSignatureOutOfRange: return "signature element %0 at location (%1,%2) size (%3,%4) is out of range.";
  89. case hlsl::ValidationRule::MetaSignatureIndexConflict: return "signature element %0 at location (%1,%2) size (%3,%4) has an indexing conflict with another signature element packed into the same row.";
  90. case hlsl::ValidationRule::MetaSignatureIllegalComponentOrder: return "signature element %0 at location (%1,%2) size (%3,%4) violates component ordering rule (arb < sv < sgv).";
  91. case hlsl::ValidationRule::MetaSignatureDataWidth: return "signature element %0 at location (%1, %2) size (%3, %4) has data width that differs from another element packed into the same row.";
  92. case hlsl::ValidationRule::MetaIntegerInterpMode: return "signature element %0 specifies invalid interpolation mode for integer component type.";
  93. case hlsl::ValidationRule::MetaInterpModeInOneRow: return "signature element %0 at location (%1,%2) size (%3,%4) has interpolation mode that differs from another element packed into the same row.";
  94. case hlsl::ValidationRule::MetaSemanticCompType: return "%0 must be %1";
  95. case hlsl::ValidationRule::MetaClipCullMaxRows: return "ClipDistance and CullDistance occupy more than the maximum of 2 rows combined.";
  96. case hlsl::ValidationRule::MetaClipCullMaxComponents: return "ClipDistance and CullDistance use more than the maximum of 8 components combined.";
  97. case hlsl::ValidationRule::MetaSignatureCompType: return "signature %0 specifies unrecognized or invalid component type";
  98. case hlsl::ValidationRule::MetaTessellatorPartition: return "Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.";
  99. case hlsl::ValidationRule::MetaTessellatorOutputPrimitive: return "Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.";
  100. case hlsl::ValidationRule::MetaMaxTessFactor: return "Hull Shader MaxTessFactor must be [%0..%1]. %2 specified";
  101. case hlsl::ValidationRule::MetaValidSamplerMode: return "Invalid sampler mode on sampler ";
  102. case hlsl::ValidationRule::MetaGlcNotOnAppendConsume: return "globallycoherent cannot be used with append/consume buffers";
  103. case hlsl::ValidationRule::MetaStructBufAlignment: return "structured buffer element size must be a multiple of %0 bytes (actual size %1 bytes)";
  104. case hlsl::ValidationRule::MetaStructBufAlignmentOutOfBound: return "structured buffer elements cannot be larger than %0 bytes (actual size %1 bytes)";
  105. case hlsl::ValidationRule::MetaEntryFunction: return "entrypoint not found";
  106. case hlsl::ValidationRule::MetaInvalidControlFlowHint: return "Invalid control flow hint";
  107. case hlsl::ValidationRule::MetaBranchFlatten: return "Can't use branch and flatten attributes together";
  108. case hlsl::ValidationRule::MetaForceCaseOnSwitch: return "Attribute forcecase only works for switch";
  109. case hlsl::ValidationRule::MetaControlFlowHintNotOnControlFlow: return "Control flow hint only works on control flow inst";
  110. case hlsl::ValidationRule::MetaTextureType: return "elements of typed buffers and textures must fit in four 32-bit quantities";
  111. case hlsl::ValidationRule::MetaBarycentricsInterpolation: return "SV_Barycentrics cannot be used with 'nointerpolation' type";
  112. case hlsl::ValidationRule::MetaBarycentricsFloat3: return "only 'float3' type is allowed for SV_Barycentrics.";
  113. case hlsl::ValidationRule::MetaBarycentricsTwoPerspectives: return "There can only be up to two input attributes of SV_Barycentrics with different perspective interpolation mode.";
  114. case hlsl::ValidationRule::MetaNoEntryPropsForEntry: return "EntryPoints must have entry properties.";
  115. case hlsl::ValidationRule::InstrOload: return "DXIL intrinsic overload must be valid";
  116. case hlsl::ValidationRule::InstrCallOload: return "Call to DXIL intrinsic '%0' does not match an allowed overload signature";
  117. case hlsl::ValidationRule::InstrPtrBitCast: return "Pointer type bitcast must be have same size";
  118. case hlsl::ValidationRule::InstrMinPrecisonBitCast: return "Bitcast on minprecison types is not allowed";
  119. case hlsl::ValidationRule::InstrStructBitCast: return "Bitcast on struct types is not allowed";
  120. case hlsl::ValidationRule::InstrStatus: return "Resource status should only used by CheckAccessFullyMapped";
  121. case hlsl::ValidationRule::InstrCheckAccessFullyMapped: return "CheckAccessFullyMapped should only used on resource status";
  122. case hlsl::ValidationRule::InstrOpConst: return "%0 of %1 must be an immediate constant";
  123. case hlsl::ValidationRule::InstrAllowed: return "Instructions must be of an allowed type";
  124. case hlsl::ValidationRule::InstrOpCodeReserved: return "Instructions must not reference reserved opcodes";
  125. case hlsl::ValidationRule::InstrOperandRange: return "expect %0 between %1, got %2";
  126. case hlsl::ValidationRule::InstrNoReadingUninitialized: return "Instructions should not read uninitialized value";
  127. case hlsl::ValidationRule::InstrNoGenericPtrAddrSpaceCast: return "Address space cast between pointer types must have one part to be generic address space";
  128. case hlsl::ValidationRule::InstrInBoundsAccess: return "Access to out-of-bounds memory is disallowed";
  129. case hlsl::ValidationRule::InstrOpConstRange: return "Constant values must be in-range for operation";
  130. case hlsl::ValidationRule::InstrImmBiasForSampleB: return "bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate";
  131. case hlsl::ValidationRule::InstrNoIndefiniteLog: return "No indefinite logarithm";
  132. case hlsl::ValidationRule::InstrNoIndefiniteAsin: return "No indefinite arcsine";
  133. case hlsl::ValidationRule::InstrNoIndefiniteAcos: return "No indefinite arccosine";
  134. case hlsl::ValidationRule::InstrNoIDivByZero: return "No signed integer division by zero";
  135. case hlsl::ValidationRule::InstrNoUDivByZero: return "No unsigned integer division by zero";
  136. case hlsl::ValidationRule::InstrNoIndefiniteDsxy: return "No indefinite derivative calculation";
  137. case hlsl::ValidationRule::InstrMinPrecisionNotPrecise: return "Instructions marked precise may not refer to minprecision values";
  138. case hlsl::ValidationRule::InstrOnlyOneAllocConsume: return "RWStructuredBuffers may increment or decrement their counters, but not both.";
  139. case hlsl::ValidationRule::InstrTextureOffset: return "offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7";
  140. case hlsl::ValidationRule::InstrCannotPullPosition: return "%0 does not support pull-model evaluation of position";
  141. case hlsl::ValidationRule::InstrEvalInterpolationMode: return "Interpolation mode on %0 used with eval_* instruction must be linear, linear_centroid, linear_noperspective, linear_noperspective_centroid, linear_sample or linear_noperspective_sample";
  142. case hlsl::ValidationRule::InstrResourceCoordinateMiss: return "coord uninitialized";
  143. case hlsl::ValidationRule::InstrResourceCoordinateTooMany: return "out of bound coord must be undef";
  144. case hlsl::ValidationRule::InstrResourceOffsetMiss: return "offset uninitialized";
  145. case hlsl::ValidationRule::InstrResourceOffsetTooMany: return "out of bound offset must be undef";
  146. case hlsl::ValidationRule::InstrUndefResultForGetDimension: return "GetDimensions used undef dimension %0 on %1";
  147. case hlsl::ValidationRule::InstrSamplerModeForLOD: return "lod instruction requires sampler declared in default mode";
  148. case hlsl::ValidationRule::InstrSamplerModeForSample: return "sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode";
  149. case hlsl::ValidationRule::InstrSamplerModeForSampleC: return "sample_c_*/gather_c instructions require sampler declared in comparison mode";
  150. case hlsl::ValidationRule::InstrSampleCompType: return "sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.";
  151. case hlsl::ValidationRule::InstrBarrierModeUselessUGroup: return "sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.";
  152. case hlsl::ValidationRule::InstrBarrierModeNoMemory: return "sync must include some form of memory barrier - _u (UAV) and/or _g (Thread Group Shared Memory). Only _t (thread group sync) is optional. ";
  153. case hlsl::ValidationRule::InstrBarrierModeForNonCS: return "sync in a non-Compute/Amplification/Mesh Shader must only sync UAV (sync_uglobal)";
  154. case hlsl::ValidationRule::InstrWriteMaskForTypedUAVStore: return "store on typed uav must write to all four components of the UAV";
  155. case hlsl::ValidationRule::InstrResourceKindForCalcLOD: return "lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray";
  156. case hlsl::ValidationRule::InstrResourceKindForSample: return "sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray";
  157. case hlsl::ValidationRule::InstrResourceKindForSampleC: return "samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray";
  158. case hlsl::ValidationRule::InstrResourceKindForGather: return "gather requires resource declared as texture/2D/Cube/2DArray/CubeArray";
  159. case hlsl::ValidationRule::InstrWriteMaskMatchValueForUAVStore: return "uav store write mask must match store value mask, write mask is %0 and store value mask is %1";
  160. case hlsl::ValidationRule::InstrResourceKindForBufferLoadStore: return "buffer load/store only works on Raw/Typed/StructuredBuffer";
  161. case hlsl::ValidationRule::InstrResourceKindForTextureStore: return "texture store only works on Texture1D/1DArray/2D/2DArray/3D";
  162. case hlsl::ValidationRule::InstrResourceKindForGetDim: return "Invalid resource kind on GetDimensions";
  163. case hlsl::ValidationRule::InstrResourceKindForTextureLoad: return "texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray";
  164. case hlsl::ValidationRule::InstrResourceClassForSamplerGather: return "sample, lod and gather should be on srv resource.";
  165. case hlsl::ValidationRule::InstrResourceClassForUAVStore: return "store should be on uav resource.";
  166. case hlsl::ValidationRule::InstrResourceClassForLoad: return "load can only run on UAV/SRV resource";
  167. case hlsl::ValidationRule::InstrResourceMapToSingleEntry: return "Fail to map resource to resource table";
  168. case hlsl::ValidationRule::InstrResourceUser: return "Resource should only used by Load/GEP/Call";
  169. case hlsl::ValidationRule::InstrResourceKindForTraceRay: return "TraceRay should only use RTAccelerationStructure";
  170. case hlsl::ValidationRule::InstrOffsetOnUAVLoad: return "uav load don't support offset";
  171. case hlsl::ValidationRule::InstrMipOnUAVLoad: return "uav load don't support mipLevel/sampleIndex";
  172. case hlsl::ValidationRule::InstrSampleIndexForLoad2DMS: return "load on Texture2DMS/2DMSArray require sampleIndex";
  173. case hlsl::ValidationRule::InstrCoordinateCountForRawTypedBuf: return "raw/typed buffer don't need 2 coordinates";
  174. case hlsl::ValidationRule::InstrCoordinateCountForStructBuf: return "structured buffer require 2 coordinates";
  175. case hlsl::ValidationRule::InstrMipLevelForGetDimension: return "Use mip level on buffer when GetDimensions";
  176. case hlsl::ValidationRule::InstrDxilStructUser: return "Dxil struct types should only used by ExtractValue";
  177. case hlsl::ValidationRule::InstrDxilStructUserOutOfBound: return "Index out of bound when extract value from dxil struct types";
  178. case hlsl::ValidationRule::InstrHandleNotFromCreateHandle: return "Resource handle should returned by createHandle";
  179. case hlsl::ValidationRule::InstrBufferUpdateCounterOnUAV: return "BufferUpdateCounter valid only on UAV";
  180. case hlsl::ValidationRule::InstrBufferUpdateCounterOnResHasCounter: return "BufferUpdateCounter valid only when HasCounter is true";
  181. case hlsl::ValidationRule::InstrCBufferOutOfBound: return "Cbuffer access out of bound";
  182. case hlsl::ValidationRule::InstrCBufferClassForCBufferHandle: return "Expect Cbuffer for CBufferLoad handle";
  183. case hlsl::ValidationRule::InstrFailToResloveTGSMPointer: return "TGSM pointers must originate from an unambiguous TGSM global variable.";
  184. case hlsl::ValidationRule::InstrExtractValue: return "ExtractValue should only be used on dxil struct types and cmpxchg";
  185. case hlsl::ValidationRule::InstrTGSMRaceCond: return "Race condition writing to shared memory detected, consider making this write conditional";
  186. case hlsl::ValidationRule::InstrAttributeAtVertexNoInterpolation: return "Attribute %0 must have nointerpolation mode in order to use GetAttributeAtVertex function.";
  187. case hlsl::ValidationRule::InstrCreateHandleImmRangeID: return "Local resource must map to global resource.";
  188. case hlsl::ValidationRule::InstrSignatureOperationNotInEntry: return "Dxil operation for input output signature must be in entryPoints.";
  189. case hlsl::ValidationRule::InstrMultipleSetMeshOutputCounts: return "SetMeshOUtputCounts cannot be called multiple times.";
  190. case hlsl::ValidationRule::InstrMissingSetMeshOutputCounts: return "Missing SetMeshOutputCounts call.";
  191. case hlsl::ValidationRule::InstrNonDominatingSetMeshOutputCounts: return "Non-Dominating SetMeshOutputCounts call.";
  192. case hlsl::ValidationRule::InstrMultipleGetMeshPayload: return "GetMeshPayload cannot be called multiple times.";
  193. case hlsl::ValidationRule::InstrNotOnceDispatchMesh: return "DispatchMesh must be called exactly once in an Amplification shader.";
  194. case hlsl::ValidationRule::InstrNonDominatingDispatchMesh: return "Non-Dominating DispatchMesh call.";
  195. case hlsl::ValidationRule::TypesNoVector: return "Vector type '%0' is not allowed";
  196. case hlsl::ValidationRule::TypesDefined: return "Type '%0' is not defined on DXIL primitives";
  197. case hlsl::ValidationRule::TypesIntWidth: return "Int type '%0' has an invalid width";
  198. case hlsl::ValidationRule::TypesNoMultiDim: return "Only one dimension allowed for array type";
  199. case hlsl::ValidationRule::TypesNoPtrToPtr: return "Pointers to pointers, or pointers in structures are not allowed";
  200. case hlsl::ValidationRule::TypesI8: return "I8 can only used as immediate value for intrinsic";
  201. case hlsl::ValidationRule::SmName: return "Unknown shader model '%0'";
  202. case hlsl::ValidationRule::SmDxilVersion: return "Shader model requires Dxil Version %0,%1";
  203. case hlsl::ValidationRule::SmOpcode: return "Opcode %0 not valid in shader model %1";
  204. case hlsl::ValidationRule::SmOperand: return "Operand must be defined in target shader model";
  205. case hlsl::ValidationRule::SmSemantic: return "Semantic '%0' is invalid as %1 %2";
  206. case hlsl::ValidationRule::SmNoInterpMode: return "Interpolation mode for '%0' is set but should be undefined";
  207. case hlsl::ValidationRule::SmConstantInterpMode: return "Interpolation mode for '%0' should be constant";
  208. case hlsl::ValidationRule::SmNoPSOutputIdx: return "Pixel shader output registers are not indexable.";
  209. case hlsl::ValidationRule::SmPSConsistentInterp: return "Interpolation mode for PS input position must be linear_noperspective_centroid or linear_noperspective_sample when outputting oDepthGE or oDepthLE and not running at sample frequency (which is forced by inputting SV_SampleIndex or declaring an input linear_sample or linear_noperspective_sample)";
  210. case hlsl::ValidationRule::SmThreadGroupChannelRange: return "Declared Thread Group %0 size %1 outside valid range [%2..%3]";
  211. case hlsl::ValidationRule::SmMaxTheadGroup: return "Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1";
  212. case hlsl::ValidationRule::SmMaxTGSMSize: return "Total Thread Group Shared Memory storage is %0, exceeded %1";
  213. case hlsl::ValidationRule::SmROVOnlyInPS: return "RasterizerOrdered objects are only allowed in 5.0+ pixel shaders";
  214. case hlsl::ValidationRule::SmTessFactorForDomain: return "Required TessFactor for domain not found declared anywhere in Patch Constant data";
  215. case hlsl::ValidationRule::SmTessFactorSizeMatchDomain: return "TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  216. case hlsl::ValidationRule::SmInsideTessFactorSizeMatchDomain: return "InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  217. case hlsl::ValidationRule::SmDomainLocationIdxOOB: return "DomainLocation component index out of bounds for the domain.";
  218. case hlsl::ValidationRule::SmHullPassThruControlPointCountMatch: return "For pass thru hull shader, input control point count must match output control point count";
  219. case hlsl::ValidationRule::SmOutputControlPointsTotalScalars: return "Total number of scalars across all HS output control points must not exceed ";
  220. case hlsl::ValidationRule::SmIsoLineOutputPrimitiveMismatch: return "Hull Shader declared with IsoLine Domain must specify output primitive point or line. Triangle_cw or triangle_ccw output are not compatible with the IsoLine Domain.";
  221. case hlsl::ValidationRule::SmTriOutputPrimitiveMismatch: return "Hull Shader declared with Tri Domain must specify output primitive point, triangle_cw or triangle_ccw. Line output is not compatible with the Tri domain";
  222. case hlsl::ValidationRule::SmValidDomain: return "Invalid Tessellator Domain specified. Must be isoline, tri or quad";
  223. case hlsl::ValidationRule::SmPatchConstantOnlyForHSDS: return "patch constant signature only valid in HS and DS";
  224. case hlsl::ValidationRule::SmStreamIndexRange: return "Stream index (%0) must between 0 and %1";
  225. case hlsl::ValidationRule::SmPSOutputSemantic: return "Pixel Shader allows output semantics to be SV_Target, SV_Depth, SV_DepthGreaterEqual, SV_DepthLessEqual, SV_Coverage or SV_StencilRef, %0 found";
  226. case hlsl::ValidationRule::SmPSMultipleDepthSemantic: return "Pixel Shader only allows one type of depth semantic to be declared";
  227. case hlsl::ValidationRule::SmPSTargetIndexMatchesRow: return "SV_Target semantic index must match packed row location";
  228. case hlsl::ValidationRule::SmPSTargetCol0: return "SV_Target packed location must start at column 0";
  229. case hlsl::ValidationRule::SmPSCoverageAndInnerCoverage: return "InnerCoverage and Coverage are mutually exclusive.";
  230. case hlsl::ValidationRule::SmGSOutputVertexCountRange: return "GS output vertex count must be [0..%0]. %1 specified";
  231. case hlsl::ValidationRule::SmGSInstanceCountRange: return "GS instance count must be [1..%0]. %1 specified";
  232. case hlsl::ValidationRule::SmDSInputControlPointCountRange: return "DS input control point count must be [0..%0]. %1 specified";
  233. case hlsl::ValidationRule::SmHSInputControlPointCountRange: return "HS input control point count must be [0..%0]. %1 specified";
  234. case hlsl::ValidationRule::SmZeroHSInputControlPointWithInput: return "When HS input control point count is 0, no input signature should exist";
  235. case hlsl::ValidationRule::SmOutputControlPointCountRange: return "output control point count must be [0..%0]. %1 specified";
  236. case hlsl::ValidationRule::SmGSValidInputPrimitive: return "GS input primitive unrecognized";
  237. case hlsl::ValidationRule::SmGSValidOutputPrimitiveTopology: return "GS output primitive topology unrecognized";
  238. case hlsl::ValidationRule::SmAppendAndConsumeOnSameUAV: return "BufferUpdateCounter inc and dec on a given UAV (%d) cannot both be in the same shader for shader model less than 5.1.";
  239. case hlsl::ValidationRule::SmInvalidTextureKindOnUAV: return "Texture2DMS[Array] or TextureCube[Array] resources are not supported with UAVs";
  240. case hlsl::ValidationRule::SmInvalidResourceKind: return "Invalid resources kind";
  241. case hlsl::ValidationRule::SmInvalidResourceCompType: return "Invalid resource return type";
  242. case hlsl::ValidationRule::SmInvalidSamplerFeedbackType: return "Invalid sampler feedback type";
  243. case hlsl::ValidationRule::SmSampleCountOnlyOn2DMS: return "Only Texture2DMS/2DMSArray could has sample count";
  244. case hlsl::ValidationRule::SmCounterOnlyOnStructBuf: return "BufferUpdateCounter valid only on structured buffers";
  245. case hlsl::ValidationRule::SmGSTotalOutputVertexDataRange: return "Declared output vertex count (%0) multiplied by the total number of declared scalar components of output data (%1) equals %2. This value cannot be greater than %3";
  246. case hlsl::ValidationRule::SmMultiStreamMustBePoint: return "Multiple GS output streams are used but '%0' is not pointlist";
  247. case hlsl::ValidationRule::SmCompletePosition: return "Not all elements of SV_Position were written";
  248. case hlsl::ValidationRule::SmUndefinedOutput: return "Not all elements of output %0 were written";
  249. case hlsl::ValidationRule::SmCSNoSignatures: return "Compute shaders must not have shader signatures.";
  250. case hlsl::ValidationRule::SmCBufferTemplateTypeMustBeStruct: return "D3D12 constant/texture buffer template element can only be a struct";
  251. case hlsl::ValidationRule::SmResourceRangeOverlap: return "Resource %0 with base %1 size %2 overlap with other resource with base %3 size %4 in space %5";
  252. case hlsl::ValidationRule::SmCBufferOffsetOverlap: return "CBuffer %0 has offset overlaps at %1";
  253. case hlsl::ValidationRule::SmCBufferElementOverflow: return "CBuffer %0 size insufficient for element at offset %1";
  254. case hlsl::ValidationRule::SmCBufferArrayOffsetAlignment: return "CBuffer %0 has unaligned array offset at %1";
  255. case hlsl::ValidationRule::SmOpcodeInInvalidFunction: return "opcode '%0' should only be used in '%1'";
  256. case hlsl::ValidationRule::SmViewIDNeedsSlot: return "Pixel shader input signature lacks available space for ViewID";
  257. case hlsl::ValidationRule::Sm64bitRawBufferLoadStore: return "i64/f64 rawBufferLoad/Store overloads are allowed after SM 6.3";
  258. case hlsl::ValidationRule::SmRayShaderSignatures: return "Ray tracing shader '%0' should not have any shader signatures";
  259. case hlsl::ValidationRule::SmRayShaderPayloadSize: return "For shader '%0', %1 size is smaller than argument's allocation size";
  260. case hlsl::ValidationRule::SmMeshShaderMaxVertexCount: return "MS max vertex output count must be [0..%0]. %1 specified";
  261. case hlsl::ValidationRule::SmMeshShaderMaxPrimitiveCount: return "MS max primitive output count must be [0..%0]. %1 specified";
  262. case hlsl::ValidationRule::SmMeshShaderPayloadSize: return "For shader '%0', payload size is greater than %1";
  263. case hlsl::ValidationRule::SmMeshShaderPayloadSizeDeclared: return "For shader '%0', payload size %1 is greater than declared size of %2 bytes";
  264. case hlsl::ValidationRule::SmMeshShaderOutputSize: return "For shader '%0', vertex plus primitive output size is greater than %1";
  265. case hlsl::ValidationRule::SmMeshShaderInOutSize: return "For shader '%0', payload plus output size is greater than %1";
  266. case hlsl::ValidationRule::SmMeshVSigRowCount: return "For shader '%0', vertex output signatures are taking up more than %1 rows";
  267. case hlsl::ValidationRule::SmMeshPSigRowCount: return "For shader '%0', primitive output signatures are taking up more than %1 rows";
  268. case hlsl::ValidationRule::SmMeshTotalSigRowCount: return "For shader '%0', vertex and primitive output signatures are taking up more than %1 rows";
  269. case hlsl::ValidationRule::SmMaxMSSMSize: return "Total Thread Group Shared Memory storage is %0, exceeded %1";
  270. case hlsl::ValidationRule::SmAmplificationShaderPayloadSize: return "For shader '%0', payload size is greater than %1";
  271. case hlsl::ValidationRule::SmAmplificationShaderPayloadSizeDeclared: return "For shader '%0', payload size %1 is greater than declared size of %2 bytes";
  272. case hlsl::ValidationRule::FlowReducible: return "Execution flow must be reducible";
  273. case hlsl::ValidationRule::FlowNoRecusion: return "Recursion is not permitted";
  274. case hlsl::ValidationRule::FlowDeadLoop: return "Loop must have break";
  275. case hlsl::ValidationRule::FlowFunctionCall: return "Function %0 with parameter is not permitted, it should be inlined";
  276. case hlsl::ValidationRule::DeclDxilNsReserved: return "Declaration '%0' uses a reserved prefix";
  277. case hlsl::ValidationRule::DeclDxilFnExtern: return "External function '%0' is not a DXIL function";
  278. case hlsl::ValidationRule::DeclUsedInternal: return "Internal declaration '%0' is unused";
  279. case hlsl::ValidationRule::DeclNotUsedExternal: return "External declaration '%0' is unused";
  280. case hlsl::ValidationRule::DeclUsedExternalFunction: return "External function '%0' is unused";
  281. case hlsl::ValidationRule::DeclFnIsCalled: return "Function '%0' is used for something other than calling";
  282. case hlsl::ValidationRule::DeclFnFlattenParam: return "Type '%0' is a struct type but is used as a parameter in function '%1'";
  283. case hlsl::ValidationRule::DeclFnAttribute: return "Function '%0' contains invalid attribute '%1' with value '%2'";
  284. case hlsl::ValidationRule::DeclResourceInFnSig: return "Function '%0' uses resource in function signature";
  285. case hlsl::ValidationRule::DeclPayloadStruct: return "Argument '%0' must be a struct type for payload in shader function '%1'";
  286. case hlsl::ValidationRule::DeclAttrStruct: return "Argument '%0' must be a struct type for attributes in shader function '%1'";
  287. case hlsl::ValidationRule::DeclParamStruct: return "Argument '%0' must be a struct type for callable shader function '%1'";
  288. case hlsl::ValidationRule::DeclExtraArgs: return "Extra argument '%0' not allowed for shader function '%1'";
  289. case hlsl::ValidationRule::DeclShaderReturnVoid: return "Shader function '%0' must have void return type";
  290. case hlsl::ValidationRule::DeclShaderMissingArg: return "%0 shader '%1' missing required %2 parameter";
  291. }
  292. // VALRULE-TEXT:END
  293. llvm_unreachable("invalid value");
  294. return "<unknown>";
  295. }
  296. namespace {
  297. // Utility class for setting and restoring the diagnostic context so we may capture errors/warnings
  298. struct DiagRestore {
  299. LLVMContext &Ctx;
  300. void *OrigDiagContext;
  301. LLVMContext::DiagnosticHandlerTy OrigHandler;
  302. DiagRestore(llvm::LLVMContext &Ctx, void *DiagContext) : Ctx(Ctx) {
  303. OrigHandler = Ctx.getDiagnosticHandler();
  304. OrigDiagContext = Ctx.getDiagnosticContext();
  305. Ctx.setDiagnosticHandler(
  306. hlsl::PrintDiagnosticContext::PrintDiagnosticHandler, DiagContext);
  307. }
  308. ~DiagRestore() {
  309. Ctx.setDiagnosticHandler(OrigHandler, OrigDiagContext);
  310. }
  311. };
  312. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  313. private:
  314. const char *m_message;
  315. public:
  316. DxilErrorDiagnosticInfo(const char *str)
  317. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  318. m_message(str) { }
  319. void print(DiagnosticPrinter &DP) const override {
  320. DP << m_message;
  321. }
  322. };
  323. static void emitDxilDiag(const LLVMContext &Ctx, const char *str) {
  324. // diagnose doesn't actually mutate anything.
  325. LLVMContext &diagCtx = const_cast<LLVMContext &>(Ctx);
  326. diagCtx.diagnose(DxilErrorDiagnosticInfo(str));
  327. }
  328. } // anon namespace
  329. namespace hlsl {
  330. // PrintDiagnosticContext methods.
  331. PrintDiagnosticContext::PrintDiagnosticContext(DiagnosticPrinter &printer)
  332. : m_Printer(printer), m_errorsFound(false), m_warningsFound(false) {}
  333. bool PrintDiagnosticContext::HasErrors() const { return m_errorsFound; }
  334. bool PrintDiagnosticContext::HasWarnings() const { return m_warningsFound; }
  335. void PrintDiagnosticContext::Handle(const DiagnosticInfo &DI) {
  336. DI.print(m_Printer);
  337. switch (DI.getSeverity()) {
  338. case llvm::DiagnosticSeverity::DS_Error:
  339. m_errorsFound = true;
  340. break;
  341. case llvm::DiagnosticSeverity::DS_Warning:
  342. m_warningsFound = true;
  343. break;
  344. default:
  345. break;
  346. }
  347. m_Printer << "\n";
  348. }
  349. void PrintDiagnosticContext::PrintDiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
  350. reinterpret_cast<hlsl::PrintDiagnosticContext *>(Context)->Handle(DI);
  351. }
  352. struct PSExecutionInfo {
  353. bool SuperSampling = false;
  354. DXIL::SemanticKind OutputDepthKind = DXIL::SemanticKind::Invalid;
  355. const InterpolationMode *PositionInterpolationMode = nullptr;
  356. };
  357. // Save status like output write for entries.
  358. struct EntryStatus {
  359. bool hasOutputPosition[DXIL::kNumOutputStreams];
  360. unsigned OutputPositionMask[DXIL::kNumOutputStreams];
  361. std::vector<unsigned> outputCols;
  362. std::vector<unsigned> patchConstOrPrimCols;
  363. bool m_bCoverageIn, m_bInnerCoverageIn;
  364. bool hasViewID;
  365. unsigned domainLocSize;
  366. EntryStatus(DxilEntryProps &entryProps)
  367. : m_bCoverageIn(false), m_bInnerCoverageIn(false), hasViewID(false) {
  368. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  369. hasOutputPosition[i] = false;
  370. OutputPositionMask[i] = 0;
  371. }
  372. outputCols.resize(entryProps.sig.OutputSignature.GetElements().size(), 0);
  373. patchConstOrPrimCols.resize(
  374. entryProps.sig.PatchConstOrPrimSignature.GetElements().size(), 0);
  375. }
  376. };
  377. struct ValidationContext {
  378. bool Failed = false;
  379. Module &M;
  380. Module *pDebugModule;
  381. DxilModule &DxilMod;
  382. const DataLayout &DL;
  383. DiagnosticPrinterRawOStream &DiagPrinter;
  384. DebugLoc LastDebugLocEmit;
  385. ValidationRule LastRuleEmit;
  386. std::unordered_set<Function *> entryFuncCallSet;
  387. std::unordered_set<Function *> patchConstFuncCallSet;
  388. std::unordered_map<unsigned, bool> UavCounterIncMap;
  389. std::unordered_map<Value *, unsigned> HandleResIndexMap;
  390. // TODO: save resource map for each createHandle/createHandleForLib.
  391. std::unordered_map<Value *, DxilResourceProperties> ResPropMap;
  392. std::unordered_map<Function *, std::vector<Function*>> PatchConstantFuncMap;
  393. std::unordered_map<Function *, std::unique_ptr<EntryStatus>> entryStatusMap;
  394. bool isLibProfile;
  395. const unsigned kDxilControlFlowHintMDKind;
  396. const unsigned kDxilPreciseMDKind;
  397. const unsigned kDxilNonUniformMDKind;
  398. const unsigned kLLVMLoopMDKind;
  399. unsigned m_DxilMajor, m_DxilMinor;
  400. ModuleSlotTracker slotTracker;
  401. ValidationContext(Module &llvmModule, Module *DebugModule,
  402. DxilModule &dxilModule,
  403. DiagnosticPrinterRawOStream &DiagPrn)
  404. : M(llvmModule), pDebugModule(DebugModule), DxilMod(dxilModule),
  405. DL(llvmModule.getDataLayout()), DiagPrinter(DiagPrn),
  406. LastRuleEmit((ValidationRule)-1),
  407. kDxilControlFlowHintMDKind(llvmModule.getContext().getMDKindID(
  408. DxilMDHelper::kDxilControlFlowHintMDName)),
  409. kDxilPreciseMDKind(llvmModule.getContext().getMDKindID(
  410. DxilMDHelper::kDxilPreciseAttributeMDName)),
  411. kDxilNonUniformMDKind(llvmModule.getContext().getMDKindID(
  412. DxilMDHelper::kDxilNonUniformAttributeMDName)),
  413. kLLVMLoopMDKind(llvmModule.getContext().getMDKindID("llvm.loop")),
  414. slotTracker(&llvmModule, true) {
  415. DxilMod.GetDxilVersion(m_DxilMajor, m_DxilMinor);
  416. for (Function &F : llvmModule.functions()) {
  417. if (DxilMod.HasDxilEntryProps(&F)) {
  418. DxilEntryProps &entryProps = DxilMod.GetDxilEntryProps(&F);
  419. entryStatusMap[&F] = llvm::make_unique<EntryStatus>(entryProps);
  420. }
  421. }
  422. isLibProfile = dxilModule.GetShaderModel()->IsLib();
  423. BuildResMap();
  424. // Collect patch constant map.
  425. if (isLibProfile) {
  426. for (Function &F : dxilModule.GetModule()->functions()) {
  427. if (dxilModule.HasDxilEntryProps(&F)) {
  428. DxilEntryProps &entryProps = dxilModule.GetDxilEntryProps(&F);
  429. DxilFunctionProps &props = entryProps.props;
  430. if (props.IsHS()) {
  431. PatchConstantFuncMap[props.ShaderProps.HS.patchConstantFunc].emplace_back(&F);
  432. }
  433. }
  434. }
  435. } else {
  436. Function *Entry = dxilModule.GetEntryFunction();
  437. if (!dxilModule.HasDxilEntryProps(Entry)) {
  438. // must have props.
  439. EmitError(ValidationRule::MetaNoEntryPropsForEntry);
  440. return;
  441. }
  442. DxilEntryProps &entryProps = dxilModule.GetDxilEntryProps(Entry);
  443. DxilFunctionProps &props = entryProps.props;
  444. if (props.IsHS()) {
  445. PatchConstantFuncMap[props.ShaderProps.HS.patchConstantFunc].emplace_back(Entry);
  446. }
  447. }
  448. }
  449. void PropagateResMap(Value *V, DxilResourceBase *Res) {
  450. auto it = ResPropMap.find(V);
  451. if (it != ResPropMap.end()) {
  452. DxilResourceProperties RP = resource_helper::loadFromResourceBase(Res);
  453. DxilResourceProperties itRP = it->second;
  454. if (itRP != RP) {
  455. EmitError(ValidationRule::InstrResourceMapToSingleEntry);
  456. }
  457. } else {
  458. DxilResourceProperties RP = resource_helper::loadFromResourceBase(Res);
  459. ResPropMap[V] = RP;
  460. for (User *U : V->users()) {
  461. if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  462. PropagateResMap(U, Res);
  463. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  464. // Stop propagate on function call.
  465. DxilInst_CreateHandleForLib hdl(CI);
  466. if (hdl) {
  467. DxilResourceProperties RP =
  468. resource_helper::loadFromResourceBase(Res);
  469. ResPropMap[CI] = RP;
  470. }
  471. } else if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  472. PropagateResMap(U, Res);
  473. } else {
  474. EmitError(ValidationRule::InstrResourceUser);
  475. }
  476. }
  477. }
  478. }
  479. void BuildResMap() {
  480. hlsl::OP *hlslOP = DxilMod.GetOP();
  481. if (isLibProfile) {
  482. std::unordered_set<Value *> ResSet;
  483. // Start from all global variable in resTab.
  484. for (auto &Res : DxilMod.GetCBuffers())
  485. PropagateResMap(Res->GetGlobalSymbol(), Res.get());
  486. for (auto &Res : DxilMod.GetUAVs())
  487. PropagateResMap(Res->GetGlobalSymbol(), Res.get());
  488. for (auto &Res : DxilMod.GetSRVs())
  489. PropagateResMap(Res->GetGlobalSymbol(), Res.get());
  490. for (auto &Res : DxilMod.GetSamplers())
  491. PropagateResMap(Res->GetGlobalSymbol(), Res.get());
  492. } else {
  493. // Scan all createHandle.
  494. for (auto &it : hlslOP->GetOpFuncList(DXIL::OpCode::CreateHandle)) {
  495. Function *F = it.second;
  496. if (!F)
  497. continue;
  498. for (User *U : F->users()) {
  499. CallInst *CI = cast<CallInst>(U);
  500. DxilInst_CreateHandle hdl(CI);
  501. // Validate Class/RangeID/Index.
  502. Value *resClass = hdl.get_resourceClass();
  503. if (!isa<ConstantInt>(resClass)) {
  504. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  505. continue;
  506. }
  507. Value *rangeIndex = hdl.get_rangeId();
  508. if (!isa<ConstantInt>(rangeIndex)) {
  509. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  510. continue;
  511. }
  512. DxilResourceBase *Res = nullptr;
  513. unsigned rangeId = hdl.get_rangeId_val();
  514. switch (
  515. static_cast<DXIL::ResourceClass>(hdl.get_resourceClass_val())) {
  516. default:
  517. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  518. continue;
  519. break;
  520. case DXIL::ResourceClass::CBuffer:
  521. if (DxilMod.GetCBuffers().size() > rangeId) {
  522. Res = &DxilMod.GetCBuffer(rangeId);
  523. } else {
  524. // Emit Error.
  525. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  526. continue;
  527. }
  528. break;
  529. case DXIL::ResourceClass::Sampler:
  530. if (DxilMod.GetSamplers().size() > rangeId) {
  531. Res = &DxilMod.GetSampler(rangeId);
  532. } else {
  533. // Emit Error.
  534. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  535. continue;
  536. }
  537. break;
  538. case DXIL::ResourceClass::SRV:
  539. if (DxilMod.GetSRVs().size() > rangeId) {
  540. Res = &DxilMod.GetSRV(rangeId);
  541. } else {
  542. // Emit Error.
  543. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  544. continue;
  545. }
  546. break;
  547. case DXIL::ResourceClass::UAV:
  548. if (DxilMod.GetUAVs().size() > rangeId) {
  549. Res = &DxilMod.GetUAV(rangeId);
  550. } else {
  551. // Emit Error.
  552. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  553. continue;
  554. }
  555. break;
  556. }
  557. ConstantInt *cIndex = dyn_cast<ConstantInt>(hdl.get_index());
  558. if (!Res->GetGlobalSymbol()
  559. ->getType()
  560. ->getPointerElementType()
  561. ->isArrayTy()) {
  562. if (!cIndex) {
  563. // index must be 0 for none array resource.
  564. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  565. continue;
  566. }
  567. }
  568. if (cIndex) {
  569. unsigned index = cIndex->getLimitedValue();
  570. if (index < Res->GetLowerBound() || index > Res->GetUpperBound()) {
  571. // index out of range.
  572. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  573. continue;
  574. }
  575. }
  576. HandleResIndexMap[CI] = rangeId;
  577. DxilResourceProperties RP = resource_helper::loadFromResourceBase(Res);
  578. ResPropMap[CI] = RP;
  579. }
  580. }
  581. }
  582. Type *ResPropTy = hlslOP->GetResourcePropertiesType();
  583. const ShaderModel &SM = *DxilMod.GetShaderModel();
  584. for (auto &it : hlslOP->GetOpFuncList(DXIL::OpCode::AnnotateHandle)) {
  585. Function *F = it.second;
  586. if (!F)
  587. continue;
  588. for (User *U : F->users()) {
  589. CallInst *CI = cast<CallInst>(U);
  590. DxilInst_AnnotateHandle hdl(CI);
  591. // Validate Class/RangeID/Index.
  592. Value *resClass = hdl.get_resourceClass();
  593. if (!isa<ConstantInt>(resClass)) {
  594. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  595. continue;
  596. }
  597. Value *resKind = hdl.get_resourceKind();
  598. if (!isa<ConstantInt>(resKind)) {
  599. EmitInstrError(CI, ValidationRule::InstrOpConstRange);
  600. continue;
  601. }
  602. DxilResourceProperties RP =
  603. resource_helper::loadFromAnnotateHandle(hdl, ResPropTy, SM);
  604. ResPropMap[CI] = RP;
  605. }
  606. }
  607. }
  608. bool HasEntryStatus(Function *F) {
  609. return entryStatusMap.find(F) != entryStatusMap.end();
  610. }
  611. EntryStatus &GetEntryStatus(Function *F) { return *entryStatusMap[F]; }
  612. DxilResourceProperties GetResourceFromVal(Value *resVal);
  613. // Provide direct access to the raw_ostream in DiagPrinter.
  614. raw_ostream &DiagStream() {
  615. struct DiagnosticPrinterRawOStream_Pub : public DiagnosticPrinterRawOStream {
  616. public:
  617. raw_ostream &DiagStream() { return Stream; }
  618. };
  619. DiagnosticPrinterRawOStream_Pub* p = (DiagnosticPrinterRawOStream_Pub*)&DiagPrinter;
  620. return p->DiagStream();
  621. }
  622. void EmitGlobalValueError(GlobalValue *GV, ValidationRule rule) {
  623. EmitFormatError(rule, { GV->getName() });
  624. }
  625. // This is the least desirable mechanism, as it has no context.
  626. void EmitError(ValidationRule rule) {
  627. DiagPrinter << GetValidationRuleText(rule) << '\n';
  628. Failed = true;
  629. }
  630. void FormatRuleText(std::string &ruleText, ArrayRef<StringRef> args) {
  631. std::string escapedArg;
  632. // Consider changing const char * to StringRef
  633. for (unsigned i = 0; i < args.size(); i++) {
  634. std::string argIdx = "%" + std::to_string(i);
  635. StringRef pArg = args[i];
  636. if (pArg == "")
  637. pArg = "<null>";
  638. if (pArg[0] == 1) {
  639. escapedArg = "";
  640. raw_string_ostream os(escapedArg);
  641. dxilutil::PrintEscapedString(pArg, os);
  642. os.flush();
  643. pArg = escapedArg;
  644. }
  645. std::string::size_type offset = ruleText.find(argIdx);
  646. if (offset == std::string::npos)
  647. continue;
  648. unsigned size = argIdx.size();
  649. ruleText.replace(offset, size, pArg);
  650. }
  651. }
  652. void EmitFormatError(ValidationRule rule, ArrayRef<StringRef> args) {
  653. std::string ruleText = GetValidationRuleText(rule);
  654. FormatRuleText(ruleText, args);
  655. DiagPrinter << ruleText << '\n';
  656. Failed = true;
  657. }
  658. void EmitMetaError(Metadata *Meta, ValidationRule rule) {
  659. DiagPrinter << GetValidationRuleText(rule);
  660. Meta->print(DiagStream(), &M);
  661. DiagPrinter << '\n';
  662. Failed = true;
  663. }
  664. void EmitResourceError(const hlsl::DxilResourceBase *Res, ValidationRule rule) {
  665. DiagPrinter << GetValidationRuleText(rule);
  666. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  667. DiagPrinter << '\n';
  668. Failed = true;
  669. }
  670. void EmitResourceFormatError(const hlsl::DxilResourceBase *Res,
  671. ValidationRule rule,
  672. ArrayRef<StringRef> args) {
  673. std::string ruleText = GetValidationRuleText(rule);
  674. FormatRuleText(ruleText, args);
  675. DiagPrinter << ruleText;
  676. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  677. DiagPrinter << '\n';
  678. Failed = true;
  679. }
  680. bool IsDebugFunctionCall(Instruction *I) {
  681. CallInst *CI = dyn_cast<CallInst>(I);
  682. return CI && CI->getCalledFunction()->getName().startswith("llvm.dbg.");
  683. }
  684. DebugLoc GetDebugLoc(Instruction *I) {
  685. DXASSERT_NOMSG(I);
  686. if (pDebugModule) {
  687. // Look up the matching instruction in the debug module.
  688. llvm::Function *Fn = I->getParent()->getParent();
  689. llvm::Function *DbgFn = pDebugModule->getFunction(Fn->getName());
  690. if (DbgFn) {
  691. // Linear lookup, but then again, failing validation is rare.
  692. inst_iterator it = inst_begin(Fn);
  693. inst_iterator dbg_it = inst_begin(DbgFn);
  694. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  695. while (&*it != I) {
  696. ++it;
  697. ++dbg_it;
  698. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  699. }
  700. return dbg_it->getDebugLoc();
  701. }
  702. }
  703. return I->getDebugLoc();
  704. }
  705. bool EmitInstrLoc(Instruction *I, ValidationRule Rule) {
  706. const DebugLoc &L = GetDebugLoc(I);
  707. if (L) {
  708. // Instructions that get scalarized will likely hit
  709. // this case. Avoid redundant diagnostic messages.
  710. if (Rule == LastRuleEmit && L == LastDebugLocEmit) {
  711. return false;
  712. }
  713. LastRuleEmit = Rule;
  714. LastDebugLocEmit = L;
  715. }
  716. // Print the error header matched by IDE regexes
  717. DiagPrinter << "error: ";
  718. // Print the debug location, if any, as matched by IDE regexes
  719. if (L) {
  720. L.print(DiagStream());
  721. DiagPrinter << ": ";
  722. }
  723. BasicBlock *BB = I->getParent();
  724. Function *F = BB->getParent();
  725. // Printthe instruction
  726. std::string InstrStr;
  727. raw_string_ostream InstrStream(InstrStr);
  728. I->print(InstrStream, slotTracker);
  729. InstrStream.flush();
  730. StringRef InstrStrRef = InstrStr;
  731. InstrStrRef = InstrStrRef.ltrim(); // Ignore indentation
  732. DiagPrinter << "at '" << InstrStrRef << "'";
  733. // Print the parent block name
  734. DiagPrinter << " in block '";
  735. if (!BB->getName().empty()) {
  736. DiagPrinter << BB->getName();
  737. }
  738. else {
  739. unsigned idx = 0;
  740. for (auto i = F->getBasicBlockList().begin(),
  741. e = F->getBasicBlockList().end(); i != e; ++i) {
  742. if (BB == &(*i)) {
  743. break;
  744. }
  745. idx++;
  746. }
  747. DiagPrinter << "#" << idx;
  748. }
  749. DiagPrinter << "'";
  750. // Print the function name
  751. DiagPrinter << " of function '" << F->getName() << "': ";
  752. // Parent will print the message
  753. return true;
  754. }
  755. void EmitInstrError(Instruction *I, ValidationRule rule) {
  756. if (!EmitInstrLoc(I, rule)) return;
  757. DiagPrinter << GetValidationRuleText(rule);
  758. DiagPrinter << '\n';
  759. if (!GetDebugLoc(I))
  760. DiagPrinter << "Use /Zi for source location.\n";
  761. Failed = true;
  762. }
  763. void EmitInstrFormatError(Instruction *I, ValidationRule rule, ArrayRef<StringRef> args) {
  764. if (!EmitInstrLoc(I, rule)) return;
  765. std::string ruleText = GetValidationRuleText(rule);
  766. FormatRuleText(ruleText, args);
  767. DiagPrinter << ruleText;
  768. DiagPrinter << '\n';
  769. if (!GetDebugLoc(I))
  770. DiagPrinter << "Use /Zi for source location.\n";
  771. Failed = true;
  772. }
  773. void EmitOperandOutOfRange(Instruction *I, StringRef name, StringRef range, StringRef v) {
  774. if (!EmitInstrLoc(I, ValidationRule::InstrOperandRange)) return;
  775. std::string ruleText = GetValidationRuleText(ValidationRule::InstrOperandRange);
  776. FormatRuleText(ruleText, {name, range, v});
  777. DiagPrinter << ruleText;
  778. DiagPrinter << '\n';
  779. if (!GetDebugLoc(I))
  780. DiagPrinter << "Use /Zi for source location.\n";
  781. Failed = true;
  782. }
  783. void EmitSignatureError(DxilSignatureElement *SE, ValidationRule rule) {
  784. EmitFormatError(rule, { SE->GetName() });
  785. }
  786. void EmitTypeError(Type *Ty, ValidationRule rule) {
  787. std::string O;
  788. raw_string_ostream OSS(O);
  789. Ty->print(OSS);
  790. EmitFormatError(rule, { OSS.str() });
  791. }
  792. void EmitFnAttributeError(Function *F, StringRef Kind, StringRef Value) {
  793. EmitFormatError(ValidationRule::DeclFnAttribute, { F->getName(), Kind, Value });
  794. }
  795. };
  796. static bool ValidateOpcodeInProfile(DXIL::OpCode opcode,
  797. DXIL::ShaderKind SK,
  798. unsigned major,
  799. unsigned minor) {
  800. unsigned op = (unsigned)opcode;
  801. /* <py::lines('VALOPCODESM-TEXT')>hctdb_instrhelp.get_valopcode_sm_text()</py>*/
  802. // VALOPCODESM-TEXT:BEGIN
  803. // Instructions: ThreadId=93, GroupId=94, ThreadIdInGroup=95,
  804. // FlattenedThreadIdInGroup=96
  805. if ((93 <= op && op <= 96))
  806. return (SK == DXIL::ShaderKind::Compute || SK == DXIL::ShaderKind::Mesh || SK == DXIL::ShaderKind::Amplification);
  807. // Instructions: DomainLocation=105
  808. if (op == 105)
  809. return (SK == DXIL::ShaderKind::Domain);
  810. // Instructions: LoadOutputControlPoint=103, LoadPatchConstant=104
  811. if ((103 <= op && op <= 104))
  812. return (SK == DXIL::ShaderKind::Domain || SK == DXIL::ShaderKind::Hull);
  813. // Instructions: EmitStream=97, CutStream=98, EmitThenCutStream=99,
  814. // GSInstanceID=100
  815. if ((97 <= op && op <= 100))
  816. return (SK == DXIL::ShaderKind::Geometry);
  817. // Instructions: PrimitiveID=108
  818. if (op == 108)
  819. return (SK == DXIL::ShaderKind::Geometry || SK == DXIL::ShaderKind::Domain || SK == DXIL::ShaderKind::Hull);
  820. // Instructions: StorePatchConstant=106, OutputControlPointID=107
  821. if ((106 <= op && op <= 107))
  822. return (SK == DXIL::ShaderKind::Hull);
  823. // Instructions: QuadReadLaneAt=122, QuadOp=123
  824. if ((122 <= op && op <= 123))
  825. return (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Compute || SK == DXIL::ShaderKind::Amplification || SK == DXIL::ShaderKind::Mesh || SK == DXIL::ShaderKind::Pixel);
  826. // Instructions: WaveIsFirstLane=110, WaveGetLaneIndex=111,
  827. // WaveGetLaneCount=112, WaveAnyTrue=113, WaveAllTrue=114,
  828. // WaveActiveAllEqual=115, WaveActiveBallot=116, WaveReadLaneAt=117,
  829. // WaveReadLaneFirst=118, WaveActiveOp=119, WaveActiveBit=120,
  830. // WavePrefixOp=121, WaveAllBitCount=135, WavePrefixBitCount=136
  831. if ((110 <= op && op <= 121) || (135 <= op && op <= 136))
  832. return (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Compute || SK == DXIL::ShaderKind::Amplification || SK == DXIL::ShaderKind::Mesh || SK == DXIL::ShaderKind::Pixel || SK == DXIL::ShaderKind::Vertex || SK == DXIL::ShaderKind::Hull || SK == DXIL::ShaderKind::Domain || SK == DXIL::ShaderKind::Geometry || SK == DXIL::ShaderKind::RayGeneration || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::Miss || SK == DXIL::ShaderKind::Callable);
  833. // Instructions: Sample=60, SampleBias=61, SampleCmp=64, CalculateLOD=81,
  834. // DerivCoarseX=83, DerivCoarseY=84, DerivFineX=85, DerivFineY=86
  835. if ((60 <= op && op <= 61) || op == 64 || op == 81 || (83 <= op && op <= 86))
  836. return (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Pixel);
  837. // Instructions: RenderTargetGetSamplePosition=76,
  838. // RenderTargetGetSampleCount=77, Discard=82, EvalSnapped=87,
  839. // EvalSampleIndex=88, EvalCentroid=89, SampleIndex=90, Coverage=91,
  840. // InnerCoverage=92
  841. if ((76 <= op && op <= 77) || op == 82 || (87 <= op && op <= 92))
  842. return (SK == DXIL::ShaderKind::Pixel);
  843. // Instructions: AttributeAtVertex=137
  844. if (op == 137)
  845. return (major > 6 || (major == 6 && minor >= 1))
  846. && (SK == DXIL::ShaderKind::Pixel);
  847. // Instructions: ViewID=138
  848. if (op == 138)
  849. return (major > 6 || (major == 6 && minor >= 1))
  850. && (SK == DXIL::ShaderKind::Vertex || SK == DXIL::ShaderKind::Hull || SK == DXIL::ShaderKind::Domain || SK == DXIL::ShaderKind::Geometry || SK == DXIL::ShaderKind::Pixel || SK == DXIL::ShaderKind::Mesh);
  851. // Instructions: RawBufferLoad=139, RawBufferStore=140
  852. if ((139 <= op && op <= 140))
  853. return (major > 6 || (major == 6 && minor >= 2));
  854. // Instructions: CreateHandleForLib=160
  855. if (op == 160)
  856. return (major > 6 || (major == 6 && minor >= 3));
  857. // Instructions: IgnoreHit=155, AcceptHitAndEndSearch=156
  858. if ((155 <= op && op <= 156))
  859. return (major > 6 || (major == 6 && minor >= 3))
  860. && (SK == DXIL::ShaderKind::AnyHit);
  861. // Instructions: CallShader=159
  862. if (op == 159)
  863. return (major > 6 || (major == 6 && minor >= 3))
  864. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::RayGeneration || SK == DXIL::ShaderKind::Miss || SK == DXIL::ShaderKind::Callable);
  865. // Instructions: ReportHit=158
  866. if (op == 158)
  867. return (major > 6 || (major == 6 && minor >= 3))
  868. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Intersection);
  869. // Instructions: InstanceID=141, InstanceIndex=142, HitKind=143,
  870. // ObjectRayOrigin=149, ObjectRayDirection=150, ObjectToWorld=151,
  871. // WorldToObject=152, PrimitiveIndex=161
  872. if ((141 <= op && op <= 143) || (149 <= op && op <= 152) || op == 161)
  873. return (major > 6 || (major == 6 && minor >= 3))
  874. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit);
  875. // Instructions: RayFlags=144, WorldRayOrigin=147, WorldRayDirection=148,
  876. // RayTMin=153, RayTCurrent=154
  877. if (op == 144 || (147 <= op && op <= 148) || (153 <= op && op <= 154))
  878. return (major > 6 || (major == 6 && minor >= 3))
  879. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::Miss);
  880. // Instructions: TraceRay=157
  881. if (op == 157)
  882. return (major > 6 || (major == 6 && minor >= 3))
  883. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::RayGeneration || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::Miss);
  884. // Instructions: DispatchRaysIndex=145, DispatchRaysDimensions=146
  885. if ((145 <= op && op <= 146))
  886. return (major > 6 || (major == 6 && minor >= 3))
  887. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::RayGeneration || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::Miss || SK == DXIL::ShaderKind::Callable);
  888. // Instructions: Dot2AddHalf=162, Dot4AddI8Packed=163, Dot4AddU8Packed=164
  889. if ((162 <= op && op <= 164))
  890. return (major > 6 || (major == 6 && minor >= 4));
  891. // Instructions: WriteSamplerFeedbackLevel=176, WriteSamplerFeedbackGrad=177,
  892. // AllocateRayQuery=178, RayQuery_TraceRayInline=179, RayQuery_Proceed=180,
  893. // RayQuery_Abort=181, RayQuery_CommitNonOpaqueTriangleHit=182,
  894. // RayQuery_CommitProceduralPrimitiveHit=183, RayQuery_CommittedStatus=184,
  895. // RayQuery_CandidateType=185, RayQuery_CandidateObjectToWorld3x4=186,
  896. // RayQuery_CandidateWorldToObject3x4=187,
  897. // RayQuery_CommittedObjectToWorld3x4=188,
  898. // RayQuery_CommittedWorldToObject3x4=189,
  899. // RayQuery_CandidateProceduralPrimitiveNonOpaque=190,
  900. // RayQuery_CandidateTriangleFrontFace=191,
  901. // RayQuery_CommittedTriangleFrontFace=192,
  902. // RayQuery_CandidateTriangleBarycentrics=193,
  903. // RayQuery_CommittedTriangleBarycentrics=194, RayQuery_RayFlags=195,
  904. // RayQuery_WorldRayOrigin=196, RayQuery_WorldRayDirection=197,
  905. // RayQuery_RayTMin=198, RayQuery_CandidateTriangleRayT=199,
  906. // RayQuery_CommittedRayT=200, RayQuery_CandidateInstanceIndex=201,
  907. // RayQuery_CandidateInstanceID=202, RayQuery_CandidateGeometryIndex=203,
  908. // RayQuery_CandidatePrimitiveIndex=204, RayQuery_CandidateObjectRayOrigin=205,
  909. // RayQuery_CandidateObjectRayDirection=206,
  910. // RayQuery_CommittedInstanceIndex=207, RayQuery_CommittedInstanceID=208,
  911. // RayQuery_CommittedGeometryIndex=209, RayQuery_CommittedPrimitiveIndex=210,
  912. // RayQuery_CommittedObjectRayOrigin=211,
  913. // RayQuery_CommittedObjectRayDirection=212,
  914. // RayQuery_CandidateInstanceContributionToHitGroupIndex=214,
  915. // RayQuery_CommittedInstanceContributionToHitGroupIndex=215
  916. if ((176 <= op && op <= 212) || (214 <= op && op <= 215))
  917. return (major > 6 || (major == 6 && minor >= 5));
  918. // Instructions: DispatchMesh=173
  919. if (op == 173)
  920. return (major > 6 || (major == 6 && minor >= 5))
  921. && (SK == DXIL::ShaderKind::Amplification);
  922. // Instructions: WaveMatch=165, WaveMultiPrefixOp=166,
  923. // WaveMultiPrefixBitCount=167
  924. if ((165 <= op && op <= 167))
  925. return (major > 6 || (major == 6 && minor >= 5))
  926. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Compute || SK == DXIL::ShaderKind::Amplification || SK == DXIL::ShaderKind::Mesh || SK == DXIL::ShaderKind::Pixel || SK == DXIL::ShaderKind::Vertex || SK == DXIL::ShaderKind::Hull || SK == DXIL::ShaderKind::Domain || SK == DXIL::ShaderKind::Geometry || SK == DXIL::ShaderKind::RayGeneration || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit || SK == DXIL::ShaderKind::Miss || SK == DXIL::ShaderKind::Callable);
  927. // Instructions: GeometryIndex=213
  928. if (op == 213)
  929. return (major > 6 || (major == 6 && minor >= 5))
  930. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Intersection || SK == DXIL::ShaderKind::AnyHit || SK == DXIL::ShaderKind::ClosestHit);
  931. // Instructions: WriteSamplerFeedback=174, WriteSamplerFeedbackBias=175
  932. if ((174 <= op && op <= 175))
  933. return (major > 6 || (major == 6 && minor >= 5))
  934. && (SK == DXIL::ShaderKind::Library || SK == DXIL::ShaderKind::Pixel);
  935. // Instructions: SetMeshOutputCounts=168, EmitIndices=169, GetMeshPayload=170,
  936. // StoreVertexOutput=171, StorePrimitiveOutput=172
  937. if ((168 <= op && op <= 172))
  938. return (major > 6 || (major == 6 && minor >= 5))
  939. && (SK == DXIL::ShaderKind::Mesh);
  940. // Instructions: CreateHandleFromHeap=216, AnnotateHandle=217
  941. if ((216 <= op && op <= 217))
  942. return (major > 6 || (major == 6 && minor >= 6));
  943. return true;
  944. // VALOPCODESM-TEXT:END
  945. }
  946. static unsigned ValidateSignatureRowCol(Instruction *I,
  947. DxilSignatureElement &SE, Value *rowVal,
  948. Value *colVal, EntryStatus &Status,
  949. ValidationContext &ValCtx) {
  950. if (ConstantInt *constRow = dyn_cast<ConstantInt>(rowVal)) {
  951. unsigned row = constRow->getLimitedValue();
  952. if (row >= SE.GetRows()) {
  953. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  954. }
  955. }
  956. if (!isa<ConstantInt>(colVal)) {
  957. // col must be const
  958. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  959. {"Col", "LoadInput/StoreOutput"});
  960. return 0;
  961. }
  962. unsigned col = cast<ConstantInt>(colVal)->getLimitedValue();
  963. if (col > SE.GetCols()) {
  964. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  965. } else {
  966. if (SE.IsOutput())
  967. Status.outputCols[SE.GetID()] |= 1 << col;
  968. if (SE.IsPatchConstOrPrim())
  969. Status.patchConstOrPrimCols[SE.GetID()] |= 1 << col;
  970. }
  971. return col;
  972. }
  973. static DxilSignatureElement *
  974. ValidateSignatureAccess(Instruction *I, DxilSignature &sig, Value *sigID,
  975. Value *rowVal, Value *colVal, EntryStatus &Status,
  976. ValidationContext &ValCtx) {
  977. if (!isa<ConstantInt>(sigID)) {
  978. // inputID must be const
  979. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  980. {"SignatureID", "LoadInput/StoreOutput"});
  981. return nullptr;
  982. }
  983. unsigned SEIdx = cast<ConstantInt>(sigID)->getLimitedValue();
  984. if (sig.GetElements().size() <= SEIdx) {
  985. ValCtx.EmitInstrError(I, ValidationRule::InstrOpConstRange);
  986. return nullptr;
  987. }
  988. DxilSignatureElement &SE = sig.GetElement(SEIdx);
  989. bool isOutput = sig.IsOutput();
  990. unsigned col = ValidateSignatureRowCol(I, SE, rowVal, colVal, Status, ValCtx);
  991. if (isOutput && SE.GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  992. unsigned mask = Status.OutputPositionMask[SE.GetOutputStream()];
  993. mask |= 1 << col;
  994. if (SE.GetOutputStream() < DXIL::kNumOutputStreams)
  995. Status.OutputPositionMask[SE.GetOutputStream()] = mask;
  996. }
  997. return &SE;
  998. }
  999. static DXIL::SamplerKind GetSamplerKind(Value *samplerHandle,
  1000. ValidationContext &ValCtx) {
  1001. if (!isa<CallInst>(samplerHandle)) {
  1002. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  1003. return DXIL::SamplerKind::Invalid;
  1004. }
  1005. DxilResourceProperties RP = ValCtx.GetResourceFromVal(samplerHandle);
  1006. if (RP.Class == DXIL::ResourceClass::Invalid) {
  1007. ValCtx.EmitInstrError(cast<CallInst>(samplerHandle),
  1008. ValidationRule::InstrHandleNotFromCreateHandle);
  1009. return DXIL::SamplerKind::Invalid;
  1010. }
  1011. if (RP.Class != DXIL::ResourceClass::Sampler) {
  1012. // must be sampler.
  1013. return DXIL::SamplerKind::Invalid;
  1014. }
  1015. if (RP.Kind == DXIL::ResourceKind::SamplerComparison)
  1016. return DXIL::SamplerKind::Comparison;
  1017. else if (RP.Kind == DXIL::ResourceKind::Invalid)
  1018. return DXIL::SamplerKind::Invalid;
  1019. else
  1020. return DXIL::SamplerKind::Default;
  1021. }
  1022. static DXIL::ResourceKind GetResourceKindAndCompTy(Value *handle, DXIL::ComponentType &CompTy, DXIL::ResourceClass &ResClass,
  1023. ValidationContext &ValCtx) {
  1024. CompTy = DXIL::ComponentType::Invalid;
  1025. ResClass = DXIL::ResourceClass::Invalid;
  1026. if (!isa<CallInst>(handle)) {
  1027. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  1028. return DXIL::ResourceKind::Invalid;
  1029. }
  1030. // TODO: validate ROV is used only in PS.
  1031. DxilResourceProperties RP = ValCtx.GetResourceFromVal(handle);
  1032. if (RP.Class == DXIL::ResourceClass::Invalid) {
  1033. ValCtx.EmitInstrError(cast<CallInst>(handle),
  1034. ValidationRule::InstrHandleNotFromCreateHandle);
  1035. return DXIL::ResourceKind::Invalid;
  1036. }
  1037. ResClass = RP.Class;
  1038. switch (ResClass) {
  1039. case DXIL::ResourceClass::SRV:
  1040. case DXIL::ResourceClass::UAV:
  1041. break;
  1042. case DXIL::ResourceClass::CBuffer:
  1043. return DXIL::ResourceKind::CBuffer;
  1044. case DXIL::ResourceClass::Sampler:
  1045. return DXIL::ResourceKind::Sampler;
  1046. default:
  1047. // Emit invalid res class
  1048. return DXIL::ResourceKind::Invalid;
  1049. }
  1050. if (!DXIL::IsStructuredBuffer(RP.Kind))
  1051. CompTy = RP.Typed.CompType;
  1052. else
  1053. CompTy = DXIL::ComponentType::Invalid;
  1054. return RP.Kind;
  1055. }
  1056. DxilFieldAnnotation *GetFieldAnnotation(Type *Ty,
  1057. DxilTypeSystem &typeSys,
  1058. std::deque<unsigned> &offsets) {
  1059. unsigned CurIdx = 1;
  1060. unsigned LastIdx = offsets.size() - 1;
  1061. DxilStructAnnotation *StructAnnot = nullptr;
  1062. for (; CurIdx < offsets.size(); ++CurIdx) {
  1063. if (const StructType *EltST = dyn_cast<StructType>(Ty)) {
  1064. if (DxilStructAnnotation *EltAnnot = typeSys.GetStructAnnotation(EltST)) {
  1065. StructAnnot = EltAnnot;
  1066. Ty = EltST->getElementType(offsets[CurIdx]);
  1067. if (CurIdx == LastIdx) {
  1068. return &StructAnnot->GetFieldAnnotation(offsets[CurIdx]);
  1069. }
  1070. } else {
  1071. return nullptr;
  1072. }
  1073. } else if (const ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  1074. Ty = AT->getElementType();
  1075. StructAnnot = nullptr;
  1076. } else {
  1077. if (StructAnnot)
  1078. return &StructAnnot->GetFieldAnnotation(offsets[CurIdx]);
  1079. }
  1080. }
  1081. return nullptr;
  1082. }
  1083. DxilResourceProperties ValidationContext::GetResourceFromVal(Value *resVal) {
  1084. auto it = ResPropMap.find(resVal);
  1085. if (it != ResPropMap.end()) {
  1086. return it->second;
  1087. }
  1088. else {
  1089. DxilResourceProperties RP;
  1090. RP.Class = DXIL::ResourceClass::Invalid;
  1091. return RP;
  1092. }
  1093. }
  1094. struct ResRetUsage {
  1095. bool x;
  1096. bool y;
  1097. bool z;
  1098. bool w;
  1099. bool status;
  1100. ResRetUsage() : x(false), y(false), z(false), w(false), status(false) {}
  1101. };
  1102. static void CollectGetDimResRetUsage(ResRetUsage &usage, Instruction *ResRet,
  1103. ValidationContext &ValCtx) {
  1104. for (User *U : ResRet->users()) {
  1105. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
  1106. for (unsigned idx : EVI->getIndices()) {
  1107. switch (idx) {
  1108. case 0:
  1109. usage.x = true;
  1110. break;
  1111. case 1:
  1112. usage.y = true;
  1113. break;
  1114. case 2:
  1115. usage.z = true;
  1116. break;
  1117. case 3:
  1118. usage.w = true;
  1119. break;
  1120. case DXIL::kResRetStatusIndex:
  1121. usage.status = true;
  1122. break;
  1123. default:
  1124. // Emit index out of bound.
  1125. ValCtx.EmitInstrError(EVI,
  1126. ValidationRule::InstrDxilStructUserOutOfBound);
  1127. break;
  1128. }
  1129. }
  1130. } else if (PHINode *PHI = dyn_cast<PHINode>(U)) {
  1131. CollectGetDimResRetUsage(usage, PHI, ValCtx);
  1132. } else {
  1133. Instruction *User = cast<Instruction>(U);
  1134. ValCtx.EmitInstrError(User, ValidationRule::InstrDxilStructUser);
  1135. }
  1136. }
  1137. }
  1138. static void ValidateResourceCoord(CallInst *CI, DXIL::ResourceKind resKind,
  1139. ArrayRef<Value *> coords,
  1140. ValidationContext &ValCtx) {
  1141. const unsigned kMaxNumCoords = 4;
  1142. unsigned numCoords = DxilResource::GetNumCoords(resKind);
  1143. for (unsigned i = 0; i < kMaxNumCoords; i++) {
  1144. if (i < numCoords) {
  1145. if (isa<UndefValue>(coords[i])) {
  1146. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  1147. }
  1148. } else {
  1149. if (!isa<UndefValue>(coords[i])) {
  1150. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  1151. }
  1152. }
  1153. }
  1154. }
  1155. static void ValidateCalcLODResourceDimensionCoord(CallInst *CI, DXIL::ResourceKind resKind,
  1156. ArrayRef<Value *> coords,
  1157. ValidationContext &ValCtx) {
  1158. const unsigned kMaxNumDimCoords = 3;
  1159. unsigned numCoords = DxilResource::GetNumDimensionsForCalcLOD(resKind);
  1160. for (unsigned i = 0; i < kMaxNumDimCoords; i++) {
  1161. if (i < numCoords) {
  1162. if (isa<UndefValue>(coords[i])) {
  1163. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  1164. }
  1165. } else {
  1166. if (!isa<UndefValue>(coords[i])) {
  1167. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  1168. }
  1169. }
  1170. }
  1171. }
  1172. static void ValidateResourceOffset(CallInst *CI, DXIL::ResourceKind resKind,
  1173. ArrayRef<Value *> offsets,
  1174. ValidationContext &ValCtx) {
  1175. const unsigned kMaxNumOffsets = 3;
  1176. unsigned numOffsets = DxilResource::GetNumOffsets(resKind);
  1177. bool hasOffset = !isa<UndefValue>(offsets[0]);
  1178. auto validateOffset = [&](Value *offset) {
  1179. if (ConstantInt *cOffset = dyn_cast<ConstantInt>(offset)) {
  1180. int offset = cOffset->getValue().getSExtValue();
  1181. if (offset > 7 || offset < -8) {
  1182. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  1183. }
  1184. } else {
  1185. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  1186. }
  1187. };
  1188. if (hasOffset) {
  1189. validateOffset(offsets[0]);
  1190. }
  1191. for (unsigned i = 1; i < kMaxNumOffsets; i++) {
  1192. if (i < numOffsets) {
  1193. if (hasOffset) {
  1194. if (isa<UndefValue>(offsets[i]))
  1195. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  1196. else
  1197. validateOffset(offsets[i]);
  1198. }
  1199. } else {
  1200. if (!isa<UndefValue>(offsets[i])) {
  1201. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  1202. }
  1203. }
  1204. }
  1205. }
  1206. static void ValidateSampleInst(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  1207. ArrayRef<Value *> coords,
  1208. ArrayRef<Value *> offsets,
  1209. bool IsSampleC,
  1210. ValidationContext &ValCtx) {
  1211. if (!IsSampleC) {
  1212. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1213. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  1214. }
  1215. } else {
  1216. if (GetSamplerKind(samplerHandle, ValCtx) !=
  1217. DXIL::SamplerKind::Comparison) {
  1218. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  1219. }
  1220. }
  1221. DXIL::ComponentType compTy;
  1222. DXIL::ResourceClass resClass;
  1223. DXIL::ResourceKind resKind =
  1224. GetResourceKindAndCompTy(srvHandle, compTy, resClass, ValCtx);
  1225. bool isSampleCompTy = compTy == DXIL::ComponentType::F32;
  1226. isSampleCompTy |= compTy == DXIL::ComponentType::SNormF32;
  1227. isSampleCompTy |= compTy == DXIL::ComponentType::UNormF32;
  1228. isSampleCompTy |= compTy == DXIL::ComponentType::F16;
  1229. isSampleCompTy |= compTy == DXIL::ComponentType::SNormF16;
  1230. isSampleCompTy |= compTy == DXIL::ComponentType::UNormF16;
  1231. if (!isSampleCompTy) {
  1232. ValCtx.EmitInstrError(CI, ValidationRule::InstrSampleCompType);
  1233. }
  1234. if (resClass != DXIL::ResourceClass::SRV) {
  1235. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  1236. }
  1237. ValidationRule rule = ValidationRule::InstrResourceKindForSample;
  1238. if (IsSampleC) {
  1239. rule = ValidationRule::InstrResourceKindForSampleC;
  1240. }
  1241. switch (resKind) {
  1242. case DXIL::ResourceKind::Texture1D:
  1243. case DXIL::ResourceKind::Texture1DArray:
  1244. case DXIL::ResourceKind::Texture2D:
  1245. case DXIL::ResourceKind::Texture2DArray:
  1246. case DXIL::ResourceKind::TextureCube:
  1247. case DXIL::ResourceKind::TextureCubeArray:
  1248. break;
  1249. case DXIL::ResourceKind::Texture3D:
  1250. if (IsSampleC) {
  1251. ValCtx.EmitInstrError(CI, rule);
  1252. }
  1253. break;
  1254. default:
  1255. ValCtx.EmitInstrError(CI, rule);
  1256. return;
  1257. }
  1258. // Coord match resource kind.
  1259. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  1260. // Offset match resource kind.
  1261. ValidateResourceOffset(CI, resKind, offsets, ValCtx);
  1262. }
  1263. static void ValidateGather(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  1264. ArrayRef<Value *> coords,
  1265. ArrayRef<Value *> offsets,
  1266. bool IsSampleC,
  1267. ValidationContext &ValCtx) {
  1268. if (!IsSampleC) {
  1269. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1270. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  1271. }
  1272. } else {
  1273. if (GetSamplerKind(samplerHandle, ValCtx) !=
  1274. DXIL::SamplerKind::Comparison) {
  1275. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  1276. }
  1277. }
  1278. DXIL::ComponentType compTy;
  1279. DXIL::ResourceClass resClass;
  1280. DXIL::ResourceKind resKind =
  1281. GetResourceKindAndCompTy(srvHandle, compTy, resClass, ValCtx);
  1282. if (resClass != DXIL::ResourceClass::SRV) {
  1283. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  1284. return;
  1285. }
  1286. // Coord match resource kind.
  1287. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  1288. // Offset match resource kind.
  1289. switch (resKind) {
  1290. case DXIL::ResourceKind::Texture2D:
  1291. case DXIL::ResourceKind::Texture2DArray: {
  1292. bool hasOffset = !isa<UndefValue>(offsets[0]);
  1293. if (hasOffset) {
  1294. if (isa<UndefValue>(offsets[1])) {
  1295. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  1296. }
  1297. }
  1298. } break;
  1299. case DXIL::ResourceKind::TextureCube:
  1300. case DXIL::ResourceKind::TextureCubeArray: {
  1301. if (!isa<UndefValue>(offsets[0])) {
  1302. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  1303. }
  1304. if (!isa<UndefValue>(offsets[1])) {
  1305. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  1306. }
  1307. } break;
  1308. default:
  1309. // Invalid resource type for gather.
  1310. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForGather);
  1311. break;
  1312. }
  1313. }
  1314. static unsigned StoreValueToMask(ArrayRef<Value *> vals) {
  1315. unsigned mask = 0;
  1316. for (unsigned i = 0; i < 4; i++) {
  1317. if (!isa<UndefValue>(vals[i])) {
  1318. mask |= 1<<i;
  1319. }
  1320. }
  1321. return mask;
  1322. }
  1323. static int GetCBufSize(Value *cbHandle, ValidationContext &ValCtx) {
  1324. if (!isa<CallInst>(cbHandle)) {
  1325. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  1326. return -1;
  1327. }
  1328. DxilResourceProperties RP = ValCtx.GetResourceFromVal(cbHandle);
  1329. if (RP.Class == DXIL::ResourceClass::Invalid) {
  1330. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  1331. ValidationRule::InstrHandleNotFromCreateHandle);
  1332. return -1;
  1333. }
  1334. if (RP.Class != DXIL::ResourceClass::CBuffer) {
  1335. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  1336. ValidationRule::InstrCBufferClassForCBufferHandle);
  1337. return -1;
  1338. }
  1339. return RP.SizeInBytes;
  1340. }
  1341. static unsigned GetNumVertices(DXIL::InputPrimitive inputPrimitive) {
  1342. const unsigned InputPrimitiveVertexTab[] = {
  1343. 0, // Undefined = 0,
  1344. 1, // Point = 1,
  1345. 2, // Line = 2,
  1346. 3, // Triangle = 3,
  1347. 0, // Reserved4 = 4,
  1348. 0, // Reserved5 = 5,
  1349. 4, // LineWithAdjacency = 6,
  1350. 6, // TriangleWithAdjacency = 7,
  1351. 1, // ControlPointPatch1 = 8,
  1352. 2, // ControlPointPatch2 = 9,
  1353. 3, // ControlPointPatch3 = 10,
  1354. 4, // ControlPointPatch4 = 11,
  1355. 5, // ControlPointPatch5 = 12,
  1356. 6, // ControlPointPatch6 = 13,
  1357. 7, // ControlPointPatch7 = 14,
  1358. 8, // ControlPointPatch8 = 15,
  1359. 9, // ControlPointPatch9 = 16,
  1360. 10, // ControlPointPatch10 = 17,
  1361. 11, // ControlPointPatch11 = 18,
  1362. 12, // ControlPointPatch12 = 19,
  1363. 13, // ControlPointPatch13 = 20,
  1364. 14, // ControlPointPatch14 = 21,
  1365. 15, // ControlPointPatch15 = 22,
  1366. 16, // ControlPointPatch16 = 23,
  1367. 17, // ControlPointPatch17 = 24,
  1368. 18, // ControlPointPatch18 = 25,
  1369. 19, // ControlPointPatch19 = 26,
  1370. 20, // ControlPointPatch20 = 27,
  1371. 21, // ControlPointPatch21 = 28,
  1372. 22, // ControlPointPatch22 = 29,
  1373. 23, // ControlPointPatch23 = 30,
  1374. 24, // ControlPointPatch24 = 31,
  1375. 25, // ControlPointPatch25 = 32,
  1376. 26, // ControlPointPatch26 = 33,
  1377. 27, // ControlPointPatch27 = 34,
  1378. 28, // ControlPointPatch28 = 35,
  1379. 29, // ControlPointPatch29 = 36,
  1380. 30, // ControlPointPatch30 = 37,
  1381. 31, // ControlPointPatch31 = 38,
  1382. 32, // ControlPointPatch32 = 39,
  1383. 0, // LastEntry,
  1384. };
  1385. unsigned primitiveIdx = static_cast<unsigned>(inputPrimitive);
  1386. return InputPrimitiveVertexTab[primitiveIdx];
  1387. }
  1388. static void ValidateSignatureDxilOp(CallInst *CI, DXIL::OpCode opcode,
  1389. ValidationContext &ValCtx) {
  1390. Function *F = CI->getParent()->getParent();
  1391. DxilModule &DM = ValCtx.DxilMod;
  1392. bool bIsPatchConstantFunc = false;
  1393. if (!DM.HasDxilEntryProps(F)) {
  1394. auto it = ValCtx.PatchConstantFuncMap.find(F);
  1395. if (it == ValCtx.PatchConstantFuncMap.end()) {
  1396. // Missing entry props.
  1397. ValCtx.EmitInstrError(CI,
  1398. ValidationRule::InstrSignatureOperationNotInEntry);
  1399. return;
  1400. }
  1401. // Use hull entry instead of patch constant function.
  1402. F = it->second.front();
  1403. bIsPatchConstantFunc = true;
  1404. }
  1405. if (!ValCtx.HasEntryStatus(F)) {
  1406. return;
  1407. }
  1408. EntryStatus &Status = ValCtx.GetEntryStatus(F);
  1409. DxilEntryProps &EntryProps = DM.GetDxilEntryProps(F);
  1410. DxilFunctionProps &props = EntryProps.props;
  1411. DxilEntrySignature &S = EntryProps.sig;
  1412. switch (opcode) {
  1413. case DXIL::OpCode::LoadInput: {
  1414. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1415. DxilSignature &inputSig = S.InputSignature;
  1416. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1417. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1418. ValidateSignatureAccess(CI, inputSig, inputID, row, col, Status, ValCtx);
  1419. // Check vertexID in ps/vs. and none array input.
  1420. Value *vertexID =
  1421. CI->getArgOperand(DXIL::OperandIndex::kLoadInputVertexIDOpIdx);
  1422. bool usedVertexID = vertexID && !isa<UndefValue>(vertexID);
  1423. if (props.IsVS() || props.IsPS()) {
  1424. if (usedVertexID) {
  1425. // use vertexID in VS/PS input.
  1426. ValCtx.EmitInstrError(CI, ValidationRule::SmOperand);
  1427. return;
  1428. }
  1429. } else {
  1430. if (ConstantInt *cVertexID = dyn_cast<ConstantInt>(vertexID)) {
  1431. int immVertexID = cVertexID->getValue().getLimitedValue();
  1432. if (cVertexID->getValue().isNegative()) {
  1433. immVertexID = cVertexID->getValue().getSExtValue();
  1434. }
  1435. const int low = 0;
  1436. int high = 0;
  1437. if (props.IsGS()) {
  1438. DXIL::InputPrimitive inputPrimitive =
  1439. props.ShaderProps.GS.inputPrimitive;
  1440. high = GetNumVertices(inputPrimitive);
  1441. } else if (props.IsDS()) {
  1442. high = props.ShaderProps.DS.inputControlPoints;
  1443. } else if (props.IsHS()) {
  1444. high = props.ShaderProps.HS.inputControlPoints;
  1445. } else {
  1446. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1447. {"LoadInput", "VS/HS/DS/GS/PS"});
  1448. }
  1449. if (immVertexID < low || immVertexID >= high) {
  1450. std::string range = std::to_string(low) + "~" + std::to_string(high);
  1451. ValCtx.EmitOperandOutOfRange(CI, "VertexID", range,
  1452. std::to_string(immVertexID));
  1453. }
  1454. }
  1455. }
  1456. } break;
  1457. case DXIL::OpCode::DomainLocation: {
  1458. Value *colValue =
  1459. CI->getArgOperand(DXIL::OperandIndex::kDomainLocationColOpIdx);
  1460. if (!isa<ConstantInt>(colValue)) {
  1461. // col must be const
  1462. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1463. {"Col", "DomainLocation"});
  1464. } else {
  1465. unsigned col = cast<ConstantInt>(colValue)->getLimitedValue();
  1466. if (col >= Status.domainLocSize) {
  1467. ValCtx.EmitError(ValidationRule::SmDomainLocationIdxOOB);
  1468. }
  1469. }
  1470. } break;
  1471. case DXIL::OpCode::StoreOutput:
  1472. case DXIL::OpCode::StoreVertexOutput:
  1473. case DXIL::OpCode::StorePrimitiveOutput: {
  1474. Value *outputID =
  1475. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1476. DxilSignature &outputSig = opcode == DXIL::OpCode::StorePrimitiveOutput ?
  1477. S.PatchConstOrPrimSignature : S.OutputSignature;
  1478. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1479. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1480. ValidateSignatureAccess(CI, outputSig, outputID, row, col, Status, ValCtx);
  1481. } break;
  1482. case DXIL::OpCode::OutputControlPointID: {
  1483. // Only used in hull shader.
  1484. Function *func = CI->getParent()->getParent();
  1485. // Make sure this is inside hs shader entry function.
  1486. if (!(props.IsHS() && F == func)) {
  1487. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1488. {"OutputControlPointID", "hull function"});
  1489. }
  1490. } break;
  1491. case DXIL::OpCode::LoadOutputControlPoint: {
  1492. // Only used in patch constant function.
  1493. Function *func = CI->getParent()->getParent();
  1494. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1495. ValCtx.EmitFormatError(
  1496. ValidationRule::SmOpcodeInInvalidFunction,
  1497. {"LoadOutputControlPoint", "PatchConstant function"});
  1498. }
  1499. Value *outputID =
  1500. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1501. DxilSignature &outputSig = S.OutputSignature;
  1502. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1503. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1504. ValidateSignatureAccess(CI, outputSig, outputID, row, col, Status, ValCtx);
  1505. } break;
  1506. case DXIL::OpCode::StorePatchConstant: {
  1507. // Only used in patch constant function.
  1508. Function *func = CI->getParent()->getParent();
  1509. if (!bIsPatchConstantFunc) {
  1510. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1511. {"StorePatchConstant", "PatchConstant function"});
  1512. } else {
  1513. auto &hullShaders = ValCtx.PatchConstantFuncMap[func];
  1514. for (Function *F : hullShaders) {
  1515. EntryStatus &Status = ValCtx.GetEntryStatus(F);
  1516. DxilEntryProps &EntryProps = DM.GetDxilEntryProps(F);
  1517. DxilEntrySignature &S = EntryProps.sig;
  1518. Value *outputID =
  1519. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1520. DxilSignature &outputSig = S.PatchConstOrPrimSignature;
  1521. Value *row =
  1522. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1523. Value *col =
  1524. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1525. ValidateSignatureAccess(CI, outputSig, outputID, row, col, Status,
  1526. ValCtx);
  1527. }
  1528. }
  1529. } break;
  1530. case DXIL::OpCode::Coverage:
  1531. Status.m_bCoverageIn = true;
  1532. break;
  1533. case DXIL::OpCode::InnerCoverage:
  1534. Status.m_bInnerCoverageIn = true;
  1535. break;
  1536. case DXIL::OpCode::ViewID:
  1537. Status.hasViewID = true;
  1538. break;
  1539. case DXIL::OpCode::EvalCentroid:
  1540. case DXIL::OpCode::EvalSampleIndex:
  1541. case DXIL::OpCode::EvalSnapped: {
  1542. // Eval* share same operand index with load input.
  1543. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1544. DxilSignature &inputSig = S.InputSignature;
  1545. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1546. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1547. DxilSignatureElement *pSE =
  1548. ValidateSignatureAccess(CI, inputSig, inputID, row, col, Status, ValCtx);
  1549. if (pSE) {
  1550. switch (pSE->GetInterpolationMode()->GetKind()) {
  1551. case DXIL::InterpolationMode::Linear:
  1552. case DXIL::InterpolationMode::LinearNoperspective:
  1553. case DXIL::InterpolationMode::LinearCentroid:
  1554. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  1555. case DXIL::InterpolationMode::LinearSample:
  1556. case DXIL::InterpolationMode::LinearNoperspectiveSample:
  1557. break;
  1558. default:
  1559. ValCtx.EmitInstrFormatError(
  1560. CI, ValidationRule::InstrEvalInterpolationMode, {pSE->GetName()});
  1561. break;
  1562. }
  1563. if (pSE->GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  1564. ValCtx.EmitInstrFormatError(
  1565. CI, ValidationRule::InstrCannotPullPosition,
  1566. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  1567. }
  1568. }
  1569. } break;
  1570. case DXIL::OpCode::AttributeAtVertex: {
  1571. Value *Attribute = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  1572. DxilSignature &inputSig = S.InputSignature;
  1573. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1574. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1575. DxilSignatureElement *pSE =
  1576. ValidateSignatureAccess(CI, inputSig, Attribute, row, col, Status, ValCtx);
  1577. if (pSE && pSE->GetInterpolationMode()->GetKind() !=
  1578. hlsl::InterpolationMode::Kind::Constant) {
  1579. ValCtx.EmitInstrFormatError(
  1580. CI, ValidationRule::InstrAttributeAtVertexNoInterpolation,
  1581. {pSE->GetName()});
  1582. }
  1583. } break;
  1584. case DXIL::OpCode::CutStream:
  1585. case DXIL::OpCode::EmitThenCutStream:
  1586. case DXIL::OpCode::EmitStream: {
  1587. if (props.IsGS()) {
  1588. auto &GS = props.ShaderProps.GS;
  1589. unsigned streamMask = 0;
  1590. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  1591. if (GS.streamPrimitiveTopologies[i] !=
  1592. DXIL::PrimitiveTopology::Undefined) {
  1593. streamMask |= 1 << i;
  1594. }
  1595. }
  1596. Value *streamID =
  1597. CI->getArgOperand(DXIL::OperandIndex::kStreamEmitCutIDOpIdx);
  1598. if (ConstantInt *cStreamID = dyn_cast<ConstantInt>(streamID)) {
  1599. int immStreamID = cStreamID->getValue().getLimitedValue();
  1600. if (cStreamID->getValue().isNegative() || immStreamID >= 4) {
  1601. ValCtx.EmitOperandOutOfRange(CI, "StreamID","0~4",
  1602. std::to_string(immStreamID));
  1603. } else {
  1604. unsigned immMask = 1 << immStreamID;
  1605. if ((streamMask & immMask) == 0) {
  1606. std::string range;
  1607. for (unsigned i = 0; i < 4; i++) {
  1608. if (streamMask & (1 << i)) {
  1609. range += std::to_string(i) + " ";
  1610. }
  1611. }
  1612. ValCtx.EmitOperandOutOfRange(CI, "StreamID", range,
  1613. std::to_string(immStreamID));
  1614. }
  1615. }
  1616. } else {
  1617. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1618. {"StreamID", "Emit/CutStream"});
  1619. }
  1620. } else {
  1621. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1622. {"Emit/CutStream", "Geometry shader"});
  1623. }
  1624. } break;
  1625. case DXIL::OpCode::EmitIndices: {
  1626. if (!props.IsMS()) {
  1627. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1628. {"EmitIndices", "Mesh shader"});
  1629. }
  1630. } break;
  1631. case DXIL::OpCode::SetMeshOutputCounts: {
  1632. if (!props.IsMS()) {
  1633. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1634. {"SetMeshOutputCounts", "Mesh shader"});
  1635. }
  1636. } break;
  1637. case DXIL::OpCode::GetMeshPayload: {
  1638. if (!props.IsMS()) {
  1639. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1640. {"GetMeshPayload", "Mesh shader"});
  1641. }
  1642. } break;
  1643. case DXIL::OpCode::DispatchMesh: {
  1644. if (!props.IsAS()) {
  1645. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1646. {"DispatchMesh", "Amplification shader"});
  1647. }
  1648. } break;
  1649. default:
  1650. break;
  1651. }
  1652. if (Status.m_bCoverageIn && Status.m_bInnerCoverageIn) {
  1653. ValCtx.EmitError(ValidationRule::SmPSCoverageAndInnerCoverage);
  1654. }
  1655. }
  1656. static void ValidateImmOperandForMathDxilOp(CallInst *CI, DXIL::OpCode opcode,
  1657. ValidationContext &ValCtx) {
  1658. switch (opcode) {
  1659. // Imm input value validation.
  1660. case DXIL::OpCode::Asin: {
  1661. DxilInst_Asin I(CI);
  1662. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1663. if (imm->getValueAPF().isInfinity()) {
  1664. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAsin);
  1665. }
  1666. }
  1667. } break;
  1668. case DXIL::OpCode::Acos: {
  1669. DxilInst_Acos I(CI);
  1670. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1671. if (imm->getValueAPF().isInfinity()) {
  1672. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAcos);
  1673. }
  1674. }
  1675. } break;
  1676. case DXIL::OpCode::Log: {
  1677. DxilInst_Log I(CI);
  1678. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1679. if (imm->getValueAPF().isInfinity()) {
  1680. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteLog);
  1681. }
  1682. }
  1683. } break;
  1684. case DXIL::OpCode::DerivFineX:
  1685. case DXIL::OpCode::DerivFineY:
  1686. case DXIL::OpCode::DerivCoarseX:
  1687. case DXIL::OpCode::DerivCoarseY: {
  1688. Value *V = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1689. if (ConstantFP *imm = dyn_cast<ConstantFP>(V)) {
  1690. if (imm->getValueAPF().isInfinity()) {
  1691. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteDsxy);
  1692. }
  1693. }
  1694. } break;
  1695. default:
  1696. break;
  1697. }
  1698. }
  1699. static void ValidateResourceDxilOp(CallInst *CI, DXIL::OpCode opcode,
  1700. ValidationContext &ValCtx) {
  1701. switch (opcode) {
  1702. case DXIL::OpCode::GetDimensions: {
  1703. DxilInst_GetDimensions getDim(CI);
  1704. Value *handle = getDim.get_handle();
  1705. DXIL::ComponentType compTy;
  1706. DXIL::ResourceClass resClass;
  1707. DXIL::ResourceKind resKind =
  1708. GetResourceKindAndCompTy(handle, compTy, resClass, ValCtx);
  1709. // Check the result component use.
  1710. ResRetUsage usage;
  1711. CollectGetDimResRetUsage(usage, CI, ValCtx);
  1712. // Mip level only for texture.
  1713. switch (resKind) {
  1714. case DXIL::ResourceKind::Texture1D:
  1715. if (usage.y) {
  1716. ValCtx.EmitInstrFormatError(
  1717. CI, ValidationRule::InstrUndefResultForGetDimension,
  1718. {"y", "Texture1D"});
  1719. }
  1720. if (usage.z) {
  1721. ValCtx.EmitInstrFormatError(
  1722. CI, ValidationRule::InstrUndefResultForGetDimension,
  1723. {"z", "Texture1D"});
  1724. }
  1725. break;
  1726. case DXIL::ResourceKind::Texture1DArray:
  1727. if (usage.z) {
  1728. ValCtx.EmitInstrFormatError(
  1729. CI, ValidationRule::InstrUndefResultForGetDimension,
  1730. {"z", "Texture1DArray"});
  1731. }
  1732. break;
  1733. case DXIL::ResourceKind::Texture2D:
  1734. if (usage.z) {
  1735. ValCtx.EmitInstrFormatError(
  1736. CI, ValidationRule::InstrUndefResultForGetDimension,
  1737. {"z", "Texture2D"});
  1738. }
  1739. break;
  1740. case DXIL::ResourceKind::Texture2DArray:
  1741. break;
  1742. case DXIL::ResourceKind::Texture2DMS:
  1743. if (usage.z) {
  1744. ValCtx.EmitInstrFormatError(
  1745. CI, ValidationRule::InstrUndefResultForGetDimension,
  1746. {"z", "Texture2DMS"});
  1747. }
  1748. break;
  1749. case DXIL::ResourceKind::Texture2DMSArray:
  1750. break;
  1751. case DXIL::ResourceKind::Texture3D:
  1752. break;
  1753. case DXIL::ResourceKind::TextureCube:
  1754. if (usage.z) {
  1755. ValCtx.EmitInstrFormatError(
  1756. CI, ValidationRule::InstrUndefResultForGetDimension,
  1757. {"z", "TextureCube"});
  1758. }
  1759. break;
  1760. case DXIL::ResourceKind::TextureCubeArray:
  1761. break;
  1762. case DXIL::ResourceKind::StructuredBuffer:
  1763. case DXIL::ResourceKind::StructuredBufferWithCounter:
  1764. case DXIL::ResourceKind::RawBuffer:
  1765. case DXIL::ResourceKind::TypedBuffer:
  1766. case DXIL::ResourceKind::TBuffer: {
  1767. Value *mip = getDim.get_mipLevel();
  1768. if (!isa<UndefValue>(mip)) {
  1769. ValCtx.EmitInstrError(CI, ValidationRule::InstrMipLevelForGetDimension);
  1770. }
  1771. if (resKind != DXIL::ResourceKind::Invalid) {
  1772. if (usage.y || usage.z || usage.w) {
  1773. ValCtx.EmitInstrFormatError(
  1774. CI, ValidationRule::InstrUndefResultForGetDimension,
  1775. {"invalid", "resource"});
  1776. }
  1777. }
  1778. } break;
  1779. default: {
  1780. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForGetDim);
  1781. } break;
  1782. }
  1783. if (usage.status) {
  1784. ValCtx.EmitInstrFormatError(
  1785. CI, ValidationRule::InstrUndefResultForGetDimension,
  1786. {"invalid", "resource"});
  1787. }
  1788. } break;
  1789. case DXIL::OpCode::CalculateLOD: {
  1790. DxilInst_CalculateLOD lod(CI);
  1791. Value *samplerHandle = lod.get_sampler();
  1792. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1793. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForLOD);
  1794. }
  1795. Value *handle = lod.get_handle();
  1796. DXIL::ComponentType compTy;
  1797. DXIL::ResourceClass resClass;
  1798. DXIL::ResourceKind resKind =
  1799. GetResourceKindAndCompTy(handle, compTy, resClass, ValCtx);
  1800. if (resClass != DXIL::ResourceClass::SRV) {
  1801. ValCtx.EmitInstrError(CI,
  1802. ValidationRule::InstrResourceClassForSamplerGather);
  1803. return;
  1804. }
  1805. // Coord match resource.
  1806. ValidateCalcLODResourceDimensionCoord(
  1807. CI, resKind, {lod.get_coord0(), lod.get_coord1(), lod.get_coord2()},
  1808. ValCtx);
  1809. switch (resKind) {
  1810. case DXIL::ResourceKind::Texture1D:
  1811. case DXIL::ResourceKind::Texture1DArray:
  1812. case DXIL::ResourceKind::Texture2D:
  1813. case DXIL::ResourceKind::Texture2DArray:
  1814. case DXIL::ResourceKind::Texture3D:
  1815. case DXIL::ResourceKind::TextureCube:
  1816. case DXIL::ResourceKind::TextureCubeArray:
  1817. break;
  1818. default:
  1819. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForCalcLOD);
  1820. break;
  1821. }
  1822. } break;
  1823. case DXIL::OpCode::TextureGather: {
  1824. DxilInst_TextureGather gather(CI);
  1825. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1826. {gather.get_coord0(), gather.get_coord1(),
  1827. gather.get_coord2(), gather.get_coord3()},
  1828. {gather.get_offset0(), gather.get_offset1()},
  1829. /*IsSampleC*/ false, ValCtx);
  1830. } break;
  1831. case DXIL::OpCode::TextureGatherCmp: {
  1832. DxilInst_TextureGatherCmp gather(CI);
  1833. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1834. {gather.get_coord0(), gather.get_coord1(),
  1835. gather.get_coord2(), gather.get_coord3()},
  1836. {gather.get_offset0(), gather.get_offset1()},
  1837. /*IsSampleC*/ true, ValCtx);
  1838. } break;
  1839. case DXIL::OpCode::Sample: {
  1840. DxilInst_Sample sample(CI);
  1841. ValidateSampleInst(
  1842. CI, sample.get_srv(), sample.get_sampler(),
  1843. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1844. sample.get_coord3()},
  1845. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1846. /*IsSampleC*/ false, ValCtx);
  1847. } break;
  1848. case DXIL::OpCode::SampleCmp: {
  1849. DxilInst_SampleCmp sample(CI);
  1850. ValidateSampleInst(
  1851. CI, sample.get_srv(), sample.get_sampler(),
  1852. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1853. sample.get_coord3()},
  1854. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1855. /*IsSampleC*/ true, ValCtx);
  1856. } break;
  1857. case DXIL::OpCode::SampleCmpLevelZero: {
  1858. // sampler must be comparison mode.
  1859. DxilInst_SampleCmpLevelZero sample(CI);
  1860. ValidateSampleInst(
  1861. CI, sample.get_srv(), sample.get_sampler(),
  1862. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1863. sample.get_coord3()},
  1864. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1865. /*IsSampleC*/ true, ValCtx);
  1866. } break;
  1867. case DXIL::OpCode::SampleBias: {
  1868. DxilInst_SampleBias sample(CI);
  1869. Value *bias = sample.get_bias();
  1870. if (ConstantFP *cBias = dyn_cast<ConstantFP>(bias)) {
  1871. float fBias = cBias->getValueAPF().convertToFloat();
  1872. if (fBias < DXIL::kMinMipLodBias || fBias > DXIL::kMaxMipLodBias) {
  1873. ValCtx.EmitInstrFormatError(
  1874. CI, ValidationRule::InstrImmBiasForSampleB,
  1875. {std::to_string(DXIL::kMinMipLodBias),
  1876. std::to_string(DXIL::kMaxMipLodBias),
  1877. std::to_string(cBias->getValueAPF().convertToFloat())});
  1878. }
  1879. }
  1880. ValidateSampleInst(
  1881. CI, sample.get_srv(), sample.get_sampler(),
  1882. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1883. sample.get_coord3()},
  1884. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1885. /*IsSampleC*/ false, ValCtx);
  1886. } break;
  1887. case DXIL::OpCode::SampleGrad: {
  1888. DxilInst_SampleGrad sample(CI);
  1889. ValidateSampleInst(
  1890. CI, sample.get_srv(), sample.get_sampler(),
  1891. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1892. sample.get_coord3()},
  1893. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1894. /*IsSampleC*/ false, ValCtx);
  1895. } break;
  1896. case DXIL::OpCode::SampleLevel: {
  1897. DxilInst_SampleLevel sample(CI);
  1898. ValidateSampleInst(
  1899. CI, sample.get_srv(), sample.get_sampler(),
  1900. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1901. sample.get_coord3()},
  1902. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1903. /*IsSampleC*/ false, ValCtx);
  1904. } break;
  1905. case DXIL::OpCode::CheckAccessFullyMapped: {
  1906. Value *Src = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1907. ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Src);
  1908. if (!EVI) {
  1909. ValCtx.EmitInstrError(CI, ValidationRule::InstrCheckAccessFullyMapped);
  1910. } else {
  1911. Value *V = EVI->getOperand(0);
  1912. bool isLegal = EVI->getNumIndices() == 1 &&
  1913. EVI->getIndices()[0] == DXIL::kResRetStatusIndex &&
  1914. ValCtx.DxilMod.GetOP()->IsResRetType(V->getType());
  1915. if (!isLegal) {
  1916. ValCtx.EmitInstrError(CI, ValidationRule::InstrCheckAccessFullyMapped);
  1917. }
  1918. }
  1919. } break;
  1920. case DXIL::OpCode::BufferStore: {
  1921. DxilInst_BufferStore bufSt(CI);
  1922. DXIL::ComponentType compTy;
  1923. DXIL::ResourceClass resClass;
  1924. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  1925. bufSt.get_uav(), compTy, resClass, ValCtx);
  1926. if (resClass != DXIL::ResourceClass::UAV) {
  1927. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1928. }
  1929. ConstantInt *mask = dyn_cast<ConstantInt>(bufSt.get_mask());
  1930. if (!mask) {
  1931. // Mask for buffer store should be immediate.
  1932. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1933. {"Mask", "BufferStore"});
  1934. return;
  1935. }
  1936. unsigned uMask = mask->getLimitedValue();
  1937. unsigned stValMask =
  1938. StoreValueToMask({bufSt.get_value0(), bufSt.get_value1(),
  1939. bufSt.get_value2(), bufSt.get_value3()});
  1940. if (stValMask != uMask) {
  1941. ValCtx.EmitInstrFormatError(
  1942. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1943. {std::to_string(uMask), std::to_string(stValMask)});
  1944. }
  1945. Value *offset = bufSt.get_coord1();
  1946. switch (resKind) {
  1947. case DXIL::ResourceKind::RawBuffer:
  1948. if (!isa<UndefValue>(offset)) {
  1949. ValCtx.EmitInstrError(
  1950. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1951. }
  1952. break;
  1953. case DXIL::ResourceKind::TypedBuffer:
  1954. case DXIL::ResourceKind::TBuffer:
  1955. if (!isa<UndefValue>(offset)) {
  1956. ValCtx.EmitInstrError(
  1957. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1958. }
  1959. if (uMask != 0xf) {
  1960. ValCtx.EmitInstrError(CI,
  1961. ValidationRule::InstrWriteMaskForTypedUAVStore);
  1962. }
  1963. break;
  1964. case DXIL::ResourceKind::StructuredBuffer:
  1965. case DXIL::ResourceKind::StructuredBufferWithCounter:
  1966. if (isa<UndefValue>(offset)) {
  1967. ValCtx.EmitInstrError(CI,
  1968. ValidationRule::InstrCoordinateCountForStructBuf);
  1969. }
  1970. break;
  1971. default:
  1972. ValCtx.EmitInstrError(
  1973. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1974. break;
  1975. }
  1976. } break;
  1977. case DXIL::OpCode::TextureStore: {
  1978. DxilInst_TextureStore texSt(CI);
  1979. DXIL::ComponentType compTy;
  1980. DXIL::ResourceClass resClass;
  1981. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  1982. texSt.get_srv(), compTy, resClass, ValCtx);
  1983. if (resClass != DXIL::ResourceClass::UAV) {
  1984. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1985. }
  1986. ConstantInt *mask = dyn_cast<ConstantInt>(texSt.get_mask());
  1987. if (!mask) {
  1988. // Mask for buffer store should be immediate.
  1989. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1990. {"Mask", "TextureStore"});
  1991. return;
  1992. }
  1993. unsigned uMask = mask->getLimitedValue();
  1994. if (uMask != 0xf) {
  1995. ValCtx.EmitInstrError(CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1996. }
  1997. unsigned stValMask =
  1998. StoreValueToMask({texSt.get_value0(), texSt.get_value1(),
  1999. texSt.get_value2(), texSt.get_value3()});
  2000. if (stValMask != uMask) {
  2001. ValCtx.EmitInstrFormatError(
  2002. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  2003. {std::to_string(uMask), std::to_string(stValMask)});
  2004. }
  2005. switch (resKind) {
  2006. case DXIL::ResourceKind::Texture1D:
  2007. case DXIL::ResourceKind::Texture1DArray:
  2008. case DXIL::ResourceKind::Texture2D:
  2009. case DXIL::ResourceKind::Texture2DArray:
  2010. case DXIL::ResourceKind::Texture3D:
  2011. break;
  2012. default:
  2013. ValCtx.EmitInstrError(CI,
  2014. ValidationRule::InstrResourceKindForTextureStore);
  2015. break;
  2016. }
  2017. } break;
  2018. case DXIL::OpCode::BufferLoad: {
  2019. DxilInst_BufferLoad bufLd(CI);
  2020. DXIL::ComponentType compTy;
  2021. DXIL::ResourceClass resClass;
  2022. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  2023. bufLd.get_srv(), compTy, resClass, ValCtx);
  2024. if (resClass != DXIL::ResourceClass::SRV &&
  2025. resClass != DXIL::ResourceClass::UAV) {
  2026. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  2027. }
  2028. Value *offset = bufLd.get_wot();
  2029. switch (resKind) {
  2030. case DXIL::ResourceKind::RawBuffer:
  2031. case DXIL::ResourceKind::TypedBuffer:
  2032. case DXIL::ResourceKind::TBuffer:
  2033. if (!isa<UndefValue>(offset)) {
  2034. ValCtx.EmitInstrError(
  2035. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  2036. }
  2037. break;
  2038. case DXIL::ResourceKind::StructuredBuffer:
  2039. case DXIL::ResourceKind::StructuredBufferWithCounter:
  2040. if (isa<UndefValue>(offset)) {
  2041. ValCtx.EmitInstrError(CI,
  2042. ValidationRule::InstrCoordinateCountForStructBuf);
  2043. }
  2044. break;
  2045. default:
  2046. ValCtx.EmitInstrError(
  2047. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  2048. break;
  2049. }
  2050. } break;
  2051. case DXIL::OpCode::TextureLoad: {
  2052. DxilInst_TextureLoad texLd(CI);
  2053. DXIL::ComponentType compTy;
  2054. DXIL::ResourceClass resClass;
  2055. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  2056. texLd.get_srv(), compTy, resClass, ValCtx);
  2057. Value *mipLevel = texLd.get_mipLevelOrSampleCount();
  2058. if (resClass == DXIL::ResourceClass::UAV) {
  2059. bool noOffset = isa<UndefValue>(texLd.get_offset0());
  2060. noOffset &= isa<UndefValue>(texLd.get_offset1());
  2061. noOffset &= isa<UndefValue>(texLd.get_offset2());
  2062. if (!noOffset) {
  2063. ValCtx.EmitInstrError(CI, ValidationRule::InstrOffsetOnUAVLoad);
  2064. }
  2065. if (!isa<UndefValue>(mipLevel)) {
  2066. ValCtx.EmitInstrError(CI, ValidationRule::InstrMipOnUAVLoad);
  2067. }
  2068. } else {
  2069. if (resClass != DXIL::ResourceClass::SRV) {
  2070. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  2071. }
  2072. }
  2073. switch (resKind) {
  2074. case DXIL::ResourceKind::Texture1D:
  2075. case DXIL::ResourceKind::Texture1DArray:
  2076. case DXIL::ResourceKind::Texture2D:
  2077. case DXIL::ResourceKind::Texture2DArray:
  2078. case DXIL::ResourceKind::Texture3D:
  2079. break;
  2080. case DXIL::ResourceKind::Texture2DMS:
  2081. case DXIL::ResourceKind::Texture2DMSArray: {
  2082. if (isa<UndefValue>(mipLevel)) {
  2083. ValCtx.EmitInstrError(CI, ValidationRule::InstrSampleIndexForLoad2DMS);
  2084. }
  2085. } break;
  2086. default:
  2087. ValCtx.EmitInstrError(CI,
  2088. ValidationRule::InstrResourceKindForTextureLoad);
  2089. break;
  2090. }
  2091. } break;
  2092. case DXIL::OpCode::CBufferLoad: {
  2093. DxilInst_CBufferLoad CBLoad(CI);
  2094. Value *regIndex = CBLoad.get_byteOffset();
  2095. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  2096. int offset = cIndex->getLimitedValue();
  2097. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  2098. if (size > 0 && offset >= size) {
  2099. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  2100. }
  2101. }
  2102. } break;
  2103. case DXIL::OpCode::CBufferLoadLegacy: {
  2104. DxilInst_CBufferLoadLegacy CBLoad(CI);
  2105. Value *regIndex = CBLoad.get_regIndex();
  2106. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  2107. int offset = cIndex->getLimitedValue() * 16; // 16 bytes align
  2108. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  2109. if (size > 0 && offset >= size) {
  2110. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  2111. }
  2112. }
  2113. } break;
  2114. case DXIL::OpCode::RawBufferLoad: {
  2115. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  2116. if (!ValCtx.DxilMod.GetShaderModel()->IsSM63Plus()) {
  2117. Type *Ty = hlslOP->GetOverloadType(DXIL::OpCode::RawBufferLoad,
  2118. CI->getCalledFunction());
  2119. if (ValCtx.DL.getTypeAllocSizeInBits(Ty) > 32) {
  2120. ValCtx.EmitInstrError(CI, ValidationRule::Sm64bitRawBufferLoadStore);
  2121. }
  2122. }
  2123. DxilInst_RawBufferLoad bufLd(CI);
  2124. DXIL::ComponentType compTy;
  2125. DXIL::ResourceClass resClass;
  2126. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  2127. bufLd.get_srv(), compTy, resClass, ValCtx);
  2128. if (resClass != DXIL::ResourceClass::SRV &&
  2129. resClass != DXIL::ResourceClass::UAV) {
  2130. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  2131. }
  2132. Value *offset = bufLd.get_elementOffset();
  2133. Value *align = bufLd.get_alignment();
  2134. unsigned alignSize = 0;
  2135. if (!isa<ConstantInt>(align)) {
  2136. ValCtx.EmitInstrError(CI,
  2137. ValidationRule::InstrCoordinateCountForRawTypedBuf);
  2138. } else {
  2139. alignSize = bufLd.get_alignment_val();
  2140. }
  2141. switch (resKind) {
  2142. case DXIL::ResourceKind::RawBuffer:
  2143. if (!isa<UndefValue>(offset)) {
  2144. ValCtx.EmitInstrError(
  2145. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  2146. }
  2147. break;
  2148. case DXIL::ResourceKind::StructuredBuffer:
  2149. case DXIL::ResourceKind::StructuredBufferWithCounter:
  2150. if (isa<UndefValue>(offset)) {
  2151. ValCtx.EmitInstrError(CI,
  2152. ValidationRule::InstrCoordinateCountForStructBuf);
  2153. }
  2154. break;
  2155. default:
  2156. ValCtx.EmitInstrError(
  2157. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  2158. break;
  2159. }
  2160. } break;
  2161. case DXIL::OpCode::RawBufferStore: {
  2162. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  2163. if (!ValCtx.DxilMod.GetShaderModel()->IsSM63Plus()) {
  2164. Type *Ty = hlslOP->GetOverloadType(DXIL::OpCode::RawBufferStore,
  2165. CI->getCalledFunction());
  2166. if (ValCtx.DL.getTypeAllocSizeInBits(Ty) > 32) {
  2167. ValCtx.EmitInstrError(CI, ValidationRule::Sm64bitRawBufferLoadStore);
  2168. }
  2169. }
  2170. DxilInst_RawBufferStore bufSt(CI);
  2171. DXIL::ComponentType compTy;
  2172. DXIL::ResourceClass resClass;
  2173. DXIL::ResourceKind resKind = GetResourceKindAndCompTy(
  2174. bufSt.get_uav(), compTy, resClass, ValCtx);
  2175. if (resClass != DXIL::ResourceClass::UAV) {
  2176. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  2177. }
  2178. ConstantInt *mask = dyn_cast<ConstantInt>(bufSt.get_mask());
  2179. if (!mask) {
  2180. // Mask for buffer store should be immediate.
  2181. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  2182. {"Mask", "BufferStore"});
  2183. return;
  2184. }
  2185. unsigned uMask = mask->getLimitedValue();
  2186. unsigned stValMask =
  2187. StoreValueToMask({bufSt.get_value0(), bufSt.get_value1(),
  2188. bufSt.get_value2(), bufSt.get_value3()});
  2189. if (stValMask != uMask) {
  2190. ValCtx.EmitInstrFormatError(
  2191. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  2192. {std::to_string(uMask), std::to_string(stValMask)});
  2193. }
  2194. Value *offset = bufSt.get_elementOffset();
  2195. Value *align = bufSt.get_alignment();
  2196. unsigned alignSize = 0;
  2197. if (!isa<ConstantInt>(align)) {
  2198. ValCtx.EmitInstrError(CI,
  2199. ValidationRule::InstrCoordinateCountForRawTypedBuf);
  2200. } else {
  2201. alignSize = bufSt.get_alignment_val();
  2202. }
  2203. switch (resKind) {
  2204. case DXIL::ResourceKind::RawBuffer:
  2205. if (!isa<UndefValue>(offset)) {
  2206. ValCtx.EmitInstrError(
  2207. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  2208. }
  2209. break;
  2210. case DXIL::ResourceKind::StructuredBuffer:
  2211. case DXIL::ResourceKind::StructuredBufferWithCounter:
  2212. if (isa<UndefValue>(offset)) {
  2213. ValCtx.EmitInstrError(CI,
  2214. ValidationRule::InstrCoordinateCountForStructBuf);
  2215. }
  2216. break;
  2217. default:
  2218. ValCtx.EmitInstrError(
  2219. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  2220. break;
  2221. }
  2222. } break;
  2223. case DXIL::OpCode::TraceRay: {
  2224. DxilInst_TraceRay traceRay(CI);
  2225. Value *hdl = traceRay.get_AccelerationStructure();
  2226. DxilResourceProperties RP = ValCtx.GetResourceFromVal(hdl);
  2227. if (RP.Class == DXIL::ResourceClass::Invalid) {
  2228. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForTraceRay);
  2229. return;
  2230. }
  2231. if (RP.Kind != DXIL::ResourceKind::RTAccelerationStructure) {
  2232. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForTraceRay);
  2233. }
  2234. } break;
  2235. default:
  2236. break;
  2237. }
  2238. }
  2239. static void ValidateDxilOperationCallInProfile(CallInst *CI,
  2240. DXIL::OpCode opcode,
  2241. const ShaderModel *pSM,
  2242. ValidationContext &ValCtx) {
  2243. DXIL::ShaderKind shaderKind = pSM ? pSM->GetKind() : DXIL::ShaderKind::Invalid;
  2244. llvm::Function *F = CI->getParent()->getParent();
  2245. if (DXIL::ShaderKind::Library == shaderKind) {
  2246. if (ValCtx.DxilMod.HasDxilFunctionProps(F))
  2247. shaderKind = ValCtx.DxilMod.GetDxilFunctionProps(F).shaderKind;
  2248. else if (ValCtx.DxilMod.IsPatchConstantShader(F))
  2249. shaderKind = DXIL::ShaderKind::Hull;
  2250. }
  2251. // These shader models are treted like compute
  2252. bool isCSLike = shaderKind == DXIL::ShaderKind::Compute ||
  2253. shaderKind == DXIL::ShaderKind::Mesh ||
  2254. shaderKind == DXIL::ShaderKind::Amplification;
  2255. // Is called from a library function
  2256. bool isLibFunc = shaderKind == DXIL::ShaderKind::Library;
  2257. switch (opcode) {
  2258. // Imm input value validation.
  2259. case DXIL::OpCode::Asin:
  2260. case DXIL::OpCode::Acos:
  2261. case DXIL::OpCode::Log:
  2262. case DXIL::OpCode::DerivFineX:
  2263. case DXIL::OpCode::DerivFineY:
  2264. case DXIL::OpCode::DerivCoarseX:
  2265. case DXIL::OpCode::DerivCoarseY:
  2266. ValidateImmOperandForMathDxilOp(CI, opcode, ValCtx);
  2267. break;
  2268. // Resource validation.
  2269. case DXIL::OpCode::GetDimensions:
  2270. case DXIL::OpCode::CalculateLOD:
  2271. case DXIL::OpCode::TextureGather:
  2272. case DXIL::OpCode::TextureGatherCmp:
  2273. case DXIL::OpCode::Sample:
  2274. case DXIL::OpCode::SampleCmp:
  2275. case DXIL::OpCode::SampleCmpLevelZero:
  2276. case DXIL::OpCode::SampleBias:
  2277. case DXIL::OpCode::SampleGrad:
  2278. case DXIL::OpCode::SampleLevel:
  2279. case DXIL::OpCode::CheckAccessFullyMapped:
  2280. case DXIL::OpCode::BufferStore:
  2281. case DXIL::OpCode::TextureStore:
  2282. case DXIL::OpCode::BufferLoad:
  2283. case DXIL::OpCode::TextureLoad:
  2284. case DXIL::OpCode::CBufferLoad:
  2285. case DXIL::OpCode::CBufferLoadLegacy:
  2286. case DXIL::OpCode::RawBufferLoad:
  2287. case DXIL::OpCode::RawBufferStore:
  2288. ValidateResourceDxilOp(CI, opcode, ValCtx);
  2289. break;
  2290. // Input output.
  2291. case DXIL::OpCode::LoadInput:
  2292. case DXIL::OpCode::DomainLocation:
  2293. case DXIL::OpCode::StoreOutput:
  2294. case DXIL::OpCode::StoreVertexOutput:
  2295. case DXIL::OpCode::StorePrimitiveOutput:
  2296. case DXIL::OpCode::OutputControlPointID:
  2297. case DXIL::OpCode::LoadOutputControlPoint:
  2298. case DXIL::OpCode::StorePatchConstant:
  2299. case DXIL::OpCode::Coverage:
  2300. case DXIL::OpCode::InnerCoverage:
  2301. case DXIL::OpCode::ViewID:
  2302. case DXIL::OpCode::EvalCentroid:
  2303. case DXIL::OpCode::EvalSampleIndex:
  2304. case DXIL::OpCode::EvalSnapped:
  2305. case DXIL::OpCode::AttributeAtVertex:
  2306. case DXIL::OpCode::EmitStream:
  2307. case DXIL::OpCode::EmitThenCutStream:
  2308. case DXIL::OpCode::CutStream:
  2309. ValidateSignatureDxilOp(CI, opcode, ValCtx);
  2310. break;
  2311. // Special.
  2312. case DXIL::OpCode::BufferUpdateCounter: {
  2313. DxilInst_BufferUpdateCounter updateCounter(CI);
  2314. Value *handle = updateCounter.get_uav();
  2315. DxilResourceProperties RP = ValCtx.GetResourceFromVal(handle);
  2316. if (RP.Class != DXIL::ResourceClass::UAV) {
  2317. ValCtx.EmitInstrError(CI,
  2318. ValidationRule::InstrBufferUpdateCounterOnUAV);
  2319. }
  2320. if (!DXIL::IsStructuredBuffer(RP.Kind)) {
  2321. ValCtx.EmitInstrError(CI, ValidationRule::SmCounterOnlyOnStructBuf);
  2322. }
  2323. if (RP.Kind != DXIL::ResourceKind::StructuredBufferWithCounter) {
  2324. ValCtx.EmitInstrError(
  2325. CI, ValidationRule::InstrBufferUpdateCounterOnResHasCounter);
  2326. }
  2327. Value *inc = updateCounter.get_inc();
  2328. if (ConstantInt *cInc = dyn_cast<ConstantInt>(inc)) {
  2329. bool isInc = cInc->getLimitedValue() == 1;
  2330. if (!ValCtx.isLibProfile) {
  2331. auto it = ValCtx.HandleResIndexMap.find(handle);
  2332. if (it != ValCtx.HandleResIndexMap.end()) {
  2333. unsigned resIndex = it->second;
  2334. if (ValCtx.UavCounterIncMap.count(resIndex)) {
  2335. if (isInc != ValCtx.UavCounterIncMap[resIndex]) {
  2336. ValCtx.EmitInstrError(CI,
  2337. ValidationRule::InstrOnlyOneAllocConsume);
  2338. }
  2339. } else {
  2340. ValCtx.UavCounterIncMap[resIndex] = isInc;
  2341. }
  2342. }
  2343. } else {
  2344. // TODO: validate ValidationRule::InstrOnlyOneAllocConsume for lib
  2345. // profile.
  2346. }
  2347. } else {
  2348. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"inc", "BufferUpdateCounter"});
  2349. }
  2350. } break;
  2351. case DXIL::OpCode::Barrier: {
  2352. DxilInst_Barrier barrier(CI);
  2353. Value *mode = barrier.get_barrierMode();
  2354. ConstantInt *cMode = dyn_cast<ConstantInt>(mode);
  2355. if (!cMode) {
  2356. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  2357. {"Mode", "Barrier"});
  2358. return;
  2359. }
  2360. const unsigned uglobal =
  2361. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  2362. const unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  2363. const unsigned ut =
  2364. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  2365. unsigned barrierMode = cMode->getLimitedValue();
  2366. if (isCSLike || isLibFunc) {
  2367. bool bHasUGlobal = barrierMode & uglobal;
  2368. bool bHasGroup = barrierMode & g;
  2369. bool bHasUGroup = barrierMode & ut;
  2370. if (bHasUGlobal && bHasUGroup) {
  2371. ValCtx.EmitInstrError(CI,
  2372. ValidationRule::InstrBarrierModeUselessUGroup);
  2373. }
  2374. if (!bHasUGlobal && !bHasGroup && !bHasUGroup) {
  2375. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeNoMemory);
  2376. }
  2377. } else {
  2378. if (uglobal != barrierMode) {
  2379. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeForNonCS);
  2380. }
  2381. }
  2382. } break;
  2383. case DXIL::OpCode::CreateHandleForLib:
  2384. if (!ValCtx.isLibProfile) {
  2385. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  2386. {"CreateHandleForLib", "Library"});
  2387. }
  2388. break;
  2389. default:
  2390. // TODO: make sure every opcode is checked.
  2391. // Skip opcodes don't need special check.
  2392. break;
  2393. }
  2394. }
  2395. static bool IsDxilFunction(llvm::Function *F) {
  2396. unsigned argSize = F->arg_size();
  2397. if (argSize < 1) {
  2398. // Cannot be a DXIL operation.
  2399. return false;
  2400. }
  2401. return OP::IsDxilOpFunc(F);
  2402. }
  2403. static void ValidateExternalFunction(Function *F, ValidationContext &ValCtx) {
  2404. if (!IsDxilFunction(F) && !ValCtx.isLibProfile) {
  2405. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclDxilFnExtern);
  2406. return;
  2407. }
  2408. if (F->use_empty()) {
  2409. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclUsedExternalFunction);
  2410. return;
  2411. }
  2412. const ShaderModel *pSM = ValCtx.DxilMod.GetShaderModel();
  2413. OP *hlslOP = ValCtx.DxilMod.GetOP();
  2414. bool isDxilOp = OP::IsDxilOpFunc(F);
  2415. Type *voidTy = Type::getVoidTy(F->getContext());
  2416. for (User *user : F->users()) {
  2417. CallInst *CI = dyn_cast<CallInst>(user);
  2418. if (!CI) {
  2419. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclFnIsCalled);
  2420. continue;
  2421. }
  2422. // Skip call to external user defined function
  2423. if (!isDxilOp)
  2424. continue;
  2425. Value *argOpcode = CI->getArgOperand(0);
  2426. ConstantInt *constOpcode = dyn_cast<ConstantInt>(argOpcode);
  2427. if (!constOpcode) {
  2428. // opcode not immediate; function body will validate this error.
  2429. continue;
  2430. }
  2431. unsigned opcode = constOpcode->getLimitedValue();
  2432. if (opcode >= (unsigned)DXIL::OpCode::NumOpCodes) {
  2433. // invalid opcode; function body will validate this error.
  2434. continue;
  2435. }
  2436. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  2437. // In some cases, no overloads are provided (void is exclusive to others)
  2438. Function *dxilFunc;
  2439. if (hlslOP->IsOverloadLegal(dxilOpcode, voidTy)) {
  2440. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, voidTy);
  2441. }
  2442. else {
  2443. Type *Ty = hlslOP->GetOverloadType(dxilOpcode, CI->getCalledFunction());
  2444. try {
  2445. if (!hlslOP->IsOverloadLegal(dxilOpcode, Ty)) {
  2446. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  2447. continue;
  2448. }
  2449. }
  2450. catch (...) {
  2451. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  2452. continue;
  2453. }
  2454. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, Ty->getScalarType());
  2455. }
  2456. if (!dxilFunc) {
  2457. // Cannot find dxilFunction based on opcode and type.
  2458. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  2459. continue;
  2460. }
  2461. if (dxilFunc->getFunctionType() != F->getFunctionType()) {
  2462. ValCtx.EmitGlobalValueError(dxilFunc, ValidationRule::InstrCallOload);
  2463. continue;
  2464. }
  2465. unsigned major = pSM->GetMajor();
  2466. unsigned minor = pSM->GetMinor();
  2467. if (ValCtx.isLibProfile) {
  2468. Function *callingFunction = CI->getParent()->getParent();
  2469. DXIL::ShaderKind SK = DXIL::ShaderKind::Library;
  2470. if (ValCtx.DxilMod.HasDxilFunctionProps(callingFunction))
  2471. SK = ValCtx.DxilMod.GetDxilFunctionProps(callingFunction).shaderKind;
  2472. else if (ValCtx.DxilMod.IsPatchConstantShader(callingFunction))
  2473. SK = DXIL::ShaderKind::Hull;
  2474. if (!ValidateOpcodeInProfile(dxilOpcode, SK, major, minor)) {
  2475. // Opcode not available in profile.
  2476. // produces: "lib_6_3(ps)", or "lib_6_3(anyhit)" for shader types
  2477. // Or: "lib_6_3(lib)" for library function
  2478. std::string shaderModel = pSM->GetName();
  2479. shaderModel += std::string("(") + ShaderModel::GetKindName(SK) + ")";
  2480. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcode,
  2481. { hlslOP->GetOpCodeName(dxilOpcode), shaderModel });
  2482. continue;
  2483. }
  2484. } else {
  2485. if (!ValidateOpcodeInProfile(dxilOpcode, pSM->GetKind(), major, minor)) {
  2486. // Opcode not available in profile.
  2487. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcode,
  2488. { hlslOP->GetOpCodeName(dxilOpcode), pSM->GetName() });
  2489. continue;
  2490. }
  2491. }
  2492. // Check more detail.
  2493. ValidateDxilOperationCallInProfile(CI, dxilOpcode, pSM, ValCtx);
  2494. }
  2495. }
  2496. ///////////////////////////////////////////////////////////////////////////////
  2497. // Instruction validation functions. //
  2498. static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {
  2499. unsigned op = I.getOpcode();
  2500. /* <py::lines('OPCODE-ALLOWED')>hctdb_instrhelp.get_instrs_pred("op", lambda i: not i.is_dxil_op and i.is_allowed, "llvm_id")</py>*/
  2501. // OPCODE-ALLOWED:BEGIN
  2502. // Instructions: Ret=1, Br=2, Switch=3, Add=8, FAdd=9, Sub=10, FSub=11, Mul=12,
  2503. // FMul=13, UDiv=14, SDiv=15, FDiv=16, URem=17, SRem=18, FRem=19, Shl=20,
  2504. // LShr=21, AShr=22, And=23, Or=24, Xor=25, Alloca=26, Load=27, Store=28,
  2505. // GetElementPtr=29, AtomicCmpXchg=31, AtomicRMW=32, Trunc=33, ZExt=34,
  2506. // SExt=35, FPToUI=36, FPToSI=37, UIToFP=38, SIToFP=39, FPTrunc=40, FPExt=41,
  2507. // BitCast=44, AddrSpaceCast=45, ICmp=46, FCmp=47, PHI=48, Call=49, Select=50,
  2508. // ExtractValue=57
  2509. return (1 <= op && op <= 3) || (8 <= op && op <= 29) || (31 <= op && op <= 41) || (44 <= op && op <= 50) || op == 57;
  2510. // OPCODE-ALLOWED:END
  2511. }
  2512. static bool IsDxilBuiltinStructType(StructType *ST, hlsl::OP *hlslOP) {
  2513. if (ST == hlslOP->GetBinaryWithCarryType())
  2514. return true;
  2515. if (ST == hlslOP->GetBinaryWithTwoOutputsType())
  2516. return true;
  2517. if (ST == hlslOP->GetInt4Type())
  2518. return true;
  2519. if (ST == hlslOP->GetDimensionsType())
  2520. return true;
  2521. if (ST == hlslOP->GetHandleType())
  2522. return true;
  2523. if (ST == hlslOP->GetSamplePosType())
  2524. return true;
  2525. if (ST == hlslOP->GetSplitDoubleType())
  2526. return true;
  2527. unsigned EltNum = ST->getNumElements();
  2528. switch (EltNum) {
  2529. case 2:
  2530. case 4:
  2531. case 8: { // 2 for doubles, 8 for halfs.
  2532. Type *EltTy = ST->getElementType(0);
  2533. return ST == hlslOP->GetCBufferRetType(EltTy);
  2534. } break;
  2535. case 5: {
  2536. Type *EltTy = ST->getElementType(0);
  2537. return ST == hlslOP->GetResRetType(EltTy);
  2538. } break;
  2539. default:
  2540. return false;
  2541. }
  2542. }
  2543. // outer type may be: [ptr to][1 dim array of]( UDT struct | scalar )
  2544. // inner type (UDT struct member) may be: [N dim array of]( UDT struct | scalar )
  2545. // scalar type may be: ( float(16|32|64) | int(16|32|64) )
  2546. static bool ValidateType(Type *Ty, ValidationContext &ValCtx, bool bInner = false) {
  2547. DXASSERT_NOMSG(Ty != nullptr);
  2548. if (Ty->isPointerTy()) {
  2549. Type *EltTy = Ty->getPointerElementType();
  2550. if (bInner || EltTy->isPointerTy()) {
  2551. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoPtrToPtr);
  2552. return false;
  2553. }
  2554. Ty = EltTy;
  2555. }
  2556. if (Ty->isArrayTy()) {
  2557. Type *EltTy = Ty->getArrayElementType();
  2558. if (!bInner && isa<ArrayType>(EltTy)) {
  2559. // Outermost array should be converted to single-dim,
  2560. // but arrays inside struct are allowed to be multi-dim
  2561. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoMultiDim);
  2562. return false;
  2563. }
  2564. while (EltTy->isArrayTy())
  2565. EltTy = EltTy->getArrayElementType();
  2566. Ty = EltTy;
  2567. }
  2568. if (Ty->isStructTy()) {
  2569. bool result = true;
  2570. StructType *ST = cast<StructType>(Ty);
  2571. StringRef Name = ST->getName();
  2572. if (Name.startswith("dx.")) {
  2573. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  2574. if (IsDxilBuiltinStructType(ST, hlslOP)) {
  2575. ValCtx.EmitTypeError(Ty, ValidationRule::InstrDxilStructUser);
  2576. result = false;
  2577. }
  2578. ValCtx.EmitTypeError(Ty, ValidationRule::DeclDxilNsReserved);
  2579. result = false;
  2580. }
  2581. for (auto e : ST->elements()) {
  2582. if (!ValidateType(e, ValCtx, /*bInner*/true)) {
  2583. result = false;
  2584. }
  2585. }
  2586. return result;
  2587. }
  2588. if (Ty->isFloatTy() || Ty->isHalfTy() || Ty->isDoubleTy()) {
  2589. return true;
  2590. }
  2591. if (Ty->isIntegerTy()) {
  2592. unsigned width = Ty->getIntegerBitWidth();
  2593. if (width != 1 && width != 8 && width != 16 && width != 32 && width != 64) {
  2594. ValCtx.EmitTypeError(Ty, ValidationRule::TypesIntWidth);
  2595. return false;
  2596. }
  2597. return true;
  2598. }
  2599. // Lib profile allow all types except those hit ValidationRule::InstrDxilStructUser.
  2600. if (ValCtx.isLibProfile)
  2601. return true;
  2602. if (Ty->isVectorTy()) {
  2603. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoVector);
  2604. return false;
  2605. }
  2606. ValCtx.EmitTypeError(Ty, ValidationRule::TypesDefined);
  2607. return false;
  2608. }
  2609. static bool GetNodeOperandAsInt(ValidationContext &ValCtx, MDNode *pMD, unsigned index, uint64_t *pValue) {
  2610. *pValue = 0;
  2611. if (pMD->getNumOperands() < index) {
  2612. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2613. return false;
  2614. }
  2615. ConstantAsMetadata *C = dyn_cast<ConstantAsMetadata>(pMD->getOperand(index));
  2616. if (C == nullptr) {
  2617. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2618. return false;
  2619. }
  2620. ConstantInt *CI = dyn_cast<ConstantInt>(C->getValue());
  2621. if (CI == nullptr) {
  2622. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2623. return false;
  2624. }
  2625. *pValue = CI->getValue().getZExtValue();
  2626. return true;
  2627. }
  2628. static bool IsPrecise(Instruction &I, ValidationContext &ValCtx) {
  2629. MDNode *pMD = I.getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  2630. if (pMD == nullptr) {
  2631. return false;
  2632. }
  2633. if (pMD->getNumOperands() != 1) {
  2634. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2635. return false;
  2636. }
  2637. uint64_t val;
  2638. if (!GetNodeOperandAsInt(ValCtx, pMD, 0, &val)) {
  2639. return false;
  2640. }
  2641. if (val == 1) {
  2642. return true;
  2643. }
  2644. if (val != 0) {
  2645. ValCtx.EmitMetaError(pMD, ValidationRule::MetaValueRange);
  2646. }
  2647. return false;
  2648. }
  2649. static bool IsValueMinPrec(DxilModule &DxilMod, Value *V) {
  2650. DXASSERT(DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision,
  2651. "else caller didn't check - currently this path should never be hit "
  2652. "otherwise");
  2653. (void)(DxilMod);
  2654. Type *Ty = V->getType();
  2655. if (Ty->isIntegerTy()) {
  2656. return 16 == Ty->getIntegerBitWidth();
  2657. }
  2658. return Ty->isHalfTy();
  2659. }
  2660. static void ValidateMsIntrinsics(Function *F,
  2661. ValidationContext &ValCtx,
  2662. CallInst *setMeshOutputCounts,
  2663. CallInst *getMeshPayload) {
  2664. if (ValCtx.DxilMod.HasDxilFunctionProps(F)) {
  2665. DXIL::ShaderKind shaderKind = ValCtx.DxilMod.GetDxilFunctionProps(F).shaderKind;
  2666. if (shaderKind != DXIL::ShaderKind::Mesh)
  2667. return;
  2668. } else {
  2669. return;
  2670. }
  2671. DominatorTreeAnalysis DTA;
  2672. DominatorTree DT = DTA.run(*F);
  2673. for (auto b = F->begin(), bend = F->end(); b != bend; ++b) {
  2674. bool foundSetMeshOutputCountsInCurrentBB = false;
  2675. for (auto i = b->begin(), iend = b->end(); i != iend; ++i) {
  2676. llvm::Instruction &I = *i;
  2677. // Calls to external functions.
  2678. CallInst *CI = dyn_cast<CallInst>(&I);
  2679. if (CI) {
  2680. Function *FCalled = CI->getCalledFunction();
  2681. if (FCalled->isDeclaration()) {
  2682. // External function validation will diagnose.
  2683. if (!IsDxilFunction(FCalled)) {
  2684. continue;
  2685. }
  2686. if (CI == setMeshOutputCounts) {
  2687. foundSetMeshOutputCountsInCurrentBB = true;
  2688. }
  2689. Value *opcodeVal = CI->getOperand(0);
  2690. ConstantInt *OpcodeConst = dyn_cast<ConstantInt>(opcodeVal);
  2691. unsigned opcode = OpcodeConst->getLimitedValue();
  2692. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  2693. if (dxilOpcode == DXIL::OpCode::StoreVertexOutput ||
  2694. dxilOpcode == DXIL::OpCode::StorePrimitiveOutput ||
  2695. dxilOpcode == DXIL::OpCode::EmitIndices) {
  2696. if (setMeshOutputCounts == nullptr) {
  2697. ValCtx.EmitInstrError(&I, ValidationRule::InstrMissingSetMeshOutputCounts);
  2698. } else if (!foundSetMeshOutputCountsInCurrentBB &&
  2699. !DT.dominates(setMeshOutputCounts->getParent(), I.getParent())) {
  2700. ValCtx.EmitInstrError(&I, ValidationRule::InstrNonDominatingSetMeshOutputCounts);
  2701. }
  2702. }
  2703. }
  2704. }
  2705. }
  2706. }
  2707. if (getMeshPayload) {
  2708. PointerType *payloadPTy = cast<PointerType>(getMeshPayload->getType());
  2709. StructType *payloadTy = cast<StructType>(payloadPTy->getPointerElementType());
  2710. const DataLayout &DL = F->getParent()->getDataLayout();
  2711. unsigned payloadSize = DL.getTypeAllocSize(payloadTy);
  2712. DxilFunctionProps &prop = ValCtx.DxilMod.GetDxilFunctionProps(F);
  2713. if (payloadSize > DXIL::kMaxMSASPayloadBytes ||
  2714. prop.ShaderProps.MS.payloadSizeInBytes > DXIL::kMaxMSASPayloadBytes) {
  2715. ValCtx.EmitFormatError(ValidationRule::SmMeshShaderPayloadSize,
  2716. { F->getName(), std::to_string(DXIL::kMaxMSASPayloadBytes) });
  2717. }
  2718. if (prop.ShaderProps.MS.payloadSizeInBytes < payloadSize) {
  2719. ValCtx.EmitFormatError(ValidationRule::SmMeshShaderPayloadSizeDeclared,
  2720. { F->getName(), std::to_string(payloadSize),
  2721. std::to_string(prop.ShaderProps.MS.payloadSizeInBytes) });
  2722. }
  2723. }
  2724. }
  2725. static void ValidateAsIntrinsics(Function *F, ValidationContext &ValCtx, CallInst *dispatchMesh) {
  2726. if (ValCtx.DxilMod.HasDxilFunctionProps(F)) {
  2727. DXIL::ShaderKind shaderKind = ValCtx.DxilMod.GetDxilFunctionProps(F).shaderKind;
  2728. if (shaderKind != DXIL::ShaderKind::Amplification)
  2729. return;
  2730. if (dispatchMesh) {
  2731. DxilInst_DispatchMesh dispatchMeshCall(dispatchMesh);
  2732. Value *operandVal = dispatchMeshCall.get_payload();
  2733. Type *payloadTy = operandVal->getType();
  2734. const DataLayout &DL = F->getParent()->getDataLayout();
  2735. unsigned payloadSize = DL.getTypeAllocSize(payloadTy);
  2736. DxilFunctionProps &prop = ValCtx.DxilMod.GetDxilFunctionProps(F);
  2737. if (payloadSize > DXIL::kMaxMSASPayloadBytes ||
  2738. prop.ShaderProps.AS.payloadSizeInBytes > DXIL::kMaxMSASPayloadBytes) {
  2739. ValCtx.EmitFormatError(
  2740. ValidationRule::SmAmplificationShaderPayloadSize,
  2741. {F->getName(), std::to_string(DXIL::kMaxMSASPayloadBytes)});
  2742. }
  2743. if (prop.ShaderProps.AS.payloadSizeInBytes < payloadSize) {
  2744. ValCtx.EmitFormatError(ValidationRule::SmAmplificationShaderPayloadSizeDeclared,
  2745. { F->getName(), std::to_string(payloadSize),
  2746. std::to_string(prop.ShaderProps.AS.payloadSizeInBytes) });
  2747. }
  2748. }
  2749. }
  2750. else {
  2751. return;
  2752. }
  2753. if (dispatchMesh == nullptr) {
  2754. ValCtx.EmitError(ValidationRule::InstrNotOnceDispatchMesh);
  2755. return;
  2756. }
  2757. PostDominatorTree PDT;
  2758. PDT.runOnFunction(*F);
  2759. if (!PDT.dominates(dispatchMesh->getParent(), &F->getEntryBlock())) {
  2760. ValCtx.EmitInstrError(dispatchMesh, ValidationRule::InstrNonDominatingDispatchMesh);
  2761. }
  2762. Function *dispatchMeshFunc = dispatchMesh->getCalledFunction();
  2763. FunctionType *dispatchMeshFuncTy = dispatchMeshFunc->getFunctionType();
  2764. PointerType *payloadPTy = cast<PointerType>(dispatchMeshFuncTy->getParamType(4));
  2765. StructType *payloadTy = cast<StructType>(payloadPTy->getPointerElementType());
  2766. const DataLayout &DL = F->getParent()->getDataLayout();
  2767. unsigned payloadSize = DL.getTypeAllocSize(payloadTy);
  2768. if (payloadSize > DXIL::kMaxMSASPayloadBytes) {
  2769. ValCtx.EmitFormatError(ValidationRule::SmAmplificationShaderPayloadSize,
  2770. { F->getName(), std::to_string(DXIL::kMaxMSASPayloadBytes) });
  2771. }
  2772. }
  2773. static void ValidateControlFlowHint(BasicBlock &bb, ValidationContext &ValCtx) {
  2774. // Validate controlflow hint.
  2775. TerminatorInst *TI = bb.getTerminator();
  2776. if (!TI)
  2777. return;
  2778. MDNode *pNode = TI->getMetadata(DxilMDHelper::kDxilControlFlowHintMDName);
  2779. if (!pNode)
  2780. return;
  2781. if (pNode->getNumOperands() < 3)
  2782. return;
  2783. bool bHasBranch = false;
  2784. bool bHasFlatten = false;
  2785. bool bForceCase = false;
  2786. for (unsigned i = 2; i < pNode->getNumOperands(); i++) {
  2787. uint64_t value = 0;
  2788. if (GetNodeOperandAsInt(ValCtx, pNode, i, &value)) {
  2789. DXIL::ControlFlowHint hint = static_cast<DXIL::ControlFlowHint>(value);
  2790. switch (hint) {
  2791. case DXIL::ControlFlowHint::Flatten:
  2792. bHasFlatten = true;
  2793. break;
  2794. case DXIL::ControlFlowHint::Branch:
  2795. bHasBranch = true;
  2796. break;
  2797. case DXIL::ControlFlowHint::ForceCase:
  2798. bForceCase = true;
  2799. break;
  2800. default:
  2801. ValCtx.EmitMetaError(pNode,
  2802. ValidationRule::MetaInvalidControlFlowHint);
  2803. }
  2804. }
  2805. }
  2806. if (bHasBranch && bHasFlatten) {
  2807. ValCtx.EmitMetaError(pNode, ValidationRule::MetaBranchFlatten);
  2808. }
  2809. if (bForceCase && !isa<SwitchInst>(TI)) {
  2810. ValCtx.EmitMetaError(pNode, ValidationRule::MetaForceCaseOnSwitch);
  2811. }
  2812. }
  2813. static void ValidateTBAAMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2814. switch (Node->getNumOperands()) {
  2815. case 1: {
  2816. if (Node->getOperand(0)->getMetadataID() != Metadata::MDStringKind) {
  2817. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2818. }
  2819. } break;
  2820. case 2: {
  2821. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2822. if (!rootNode) {
  2823. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2824. } else {
  2825. ValidateTBAAMetadata(rootNode, ValCtx);
  2826. }
  2827. } break;
  2828. case 3: {
  2829. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2830. if (!rootNode) {
  2831. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2832. } else {
  2833. ValidateTBAAMetadata(rootNode, ValCtx);
  2834. }
  2835. ConstantAsMetadata *pointsToConstMem = dyn_cast<ConstantAsMetadata>(Node->getOperand(2));
  2836. if (!pointsToConstMem) {
  2837. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2838. } else {
  2839. ConstantInt *isConst = dyn_cast<ConstantInt>(pointsToConstMem->getValue());
  2840. if (!isConst) {
  2841. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2842. } else if (isConst->getValue().getLimitedValue() > 1) {
  2843. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2844. }
  2845. }
  2846. } break;
  2847. default:
  2848. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2849. }
  2850. }
  2851. static void ValidateLoopMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2852. if (Node->getNumOperands() == 0 || Node->getNumOperands() > 2) {
  2853. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2854. return;
  2855. }
  2856. if (Node != Node->getOperand(0).get()) {
  2857. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2858. return;
  2859. }
  2860. if (Node->getNumOperands() == 1) {
  2861. return;
  2862. }
  2863. MDNode *LoopNode = dyn_cast<MDNode>(Node->getOperand(1).get());
  2864. if (!LoopNode) {
  2865. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2866. return;
  2867. }
  2868. if (LoopNode->getNumOperands() < 1 || LoopNode->getNumOperands() > 2) {
  2869. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2870. return;
  2871. }
  2872. if (LoopNode->getOperand(0) == LoopNode) {
  2873. ValidateLoopMetadata(LoopNode, ValCtx);
  2874. return;
  2875. }
  2876. MDString *LoopStr = dyn_cast<MDString>(LoopNode->getOperand(0));
  2877. if (!LoopStr) {
  2878. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2879. return;
  2880. }
  2881. StringRef Name = LoopStr->getString();
  2882. if (Name != "llvm.loop.unroll.full" && Name != "llvm.loop.unroll.disable" &&
  2883. Name != "llvm.loop.unroll.count") {
  2884. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2885. return;
  2886. }
  2887. if (Name == "llvm.loop.unroll.count") {
  2888. if (LoopNode->getNumOperands() != 2) {
  2889. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2890. return;
  2891. }
  2892. ConstantAsMetadata *CountNode =
  2893. dyn_cast<ConstantAsMetadata>(LoopNode->getOperand(1));
  2894. if (!CountNode) {
  2895. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2896. } else {
  2897. ConstantInt *Count = dyn_cast<ConstantInt>(CountNode->getValue());
  2898. if (!Count) {
  2899. ValCtx.EmitMetaError(CountNode, ValidationRule::MetaWellFormed);
  2900. }
  2901. }
  2902. }
  2903. }
  2904. static void ValidateNonUniformMetadata(Instruction &I, MDNode *pMD,
  2905. ValidationContext &ValCtx) {
  2906. if (!ValCtx.isLibProfile) {
  2907. ValCtx.EmitMetaError(pMD, ValidationRule::MetaUsed);
  2908. }
  2909. if (!isa<GetElementPtrInst>(I)) {
  2910. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2911. }
  2912. if (pMD->getNumOperands() != 1) {
  2913. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2914. }
  2915. uint64_t val;
  2916. if (!GetNodeOperandAsInt(ValCtx, pMD, 0, &val)) {
  2917. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  2918. }
  2919. if (val != 1) {
  2920. ValCtx.EmitMetaError(pMD, ValidationRule::MetaValueRange);
  2921. }
  2922. }
  2923. static void ValidateInstructionMetadata(Instruction *I,
  2924. ValidationContext &ValCtx) {
  2925. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2926. I->getAllMetadataOtherThanDebugLoc(MDNodes);
  2927. for (auto &MD : MDNodes) {
  2928. if (MD.first == ValCtx.kDxilControlFlowHintMDKind) {
  2929. if (!isa<TerminatorInst>(I)) {
  2930. ValCtx.EmitInstrError(
  2931. I, ValidationRule::MetaControlFlowHintNotOnControlFlow);
  2932. }
  2933. } else if (MD.first == ValCtx.kDxilPreciseMDKind) {
  2934. // Validated in IsPrecise.
  2935. } else if (MD.first == ValCtx.kLLVMLoopMDKind) {
  2936. ValidateLoopMetadata(MD.second, ValCtx);
  2937. } else if (MD.first == LLVMContext::MD_tbaa) {
  2938. ValidateTBAAMetadata(MD.second, ValCtx);
  2939. } else if (MD.first == LLVMContext::MD_range) {
  2940. // Validated in Verifier.cpp.
  2941. } else if (MD.first == LLVMContext::MD_noalias ||
  2942. MD.first == LLVMContext::MD_alias_scope) {
  2943. // noalias for DXIL validator >= 1.2
  2944. } else if (MD.first == ValCtx.kDxilNonUniformMDKind) {
  2945. ValidateNonUniformMetadata(*I, MD.second, ValCtx);
  2946. } else {
  2947. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2948. }
  2949. }
  2950. }
  2951. static void ValidateFunctionAttribute(Function *F, ValidationContext &ValCtx) {
  2952. AttributeSet attrSet = F->getAttributes().getFnAttributes();
  2953. // fp32-denorm-mode
  2954. if (attrSet.hasAttribute(AttributeSet::FunctionIndex,
  2955. DXIL::kFP32DenormKindString)) {
  2956. Attribute attr = attrSet.getAttribute(AttributeSet::FunctionIndex,
  2957. DXIL::kFP32DenormKindString);
  2958. StringRef value = attr.getValueAsString();
  2959. if (!value.equals(DXIL::kFP32DenormValueAnyString) &&
  2960. !value.equals(DXIL::kFP32DenormValueFtzString) &&
  2961. !value.equals(DXIL::kFP32DenormValuePreserveString)) {
  2962. ValCtx.EmitFnAttributeError(F, attr.getKindAsString(),
  2963. attr.getValueAsString());
  2964. }
  2965. }
  2966. // TODO: If validating libraries, we should remove all unknown function attributes.
  2967. // For each attribute, check if it is a known attribute
  2968. for (unsigned I = 0, E = attrSet.getNumSlots(); I != E; ++I) {
  2969. for (auto AttrIter = attrSet.begin(I), AttrEnd = attrSet.end(I);
  2970. AttrIter != AttrEnd; ++AttrIter) {
  2971. if (!AttrIter->isStringAttribute()) {
  2972. continue;
  2973. }
  2974. StringRef kind = AttrIter->getKindAsString();
  2975. if (!kind.equals(DXIL::kFP32DenormKindString)) {
  2976. ValCtx.EmitFnAttributeError(F, AttrIter->getKindAsString(),
  2977. AttrIter->getValueAsString());
  2978. }
  2979. }
  2980. }
  2981. }
  2982. static void ValidateFunctionMetadata(Function *F, ValidationContext &ValCtx) {
  2983. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2984. F->getAllMetadata(MDNodes);
  2985. for (auto &MD : MDNodes) {
  2986. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2987. }
  2988. }
  2989. static bool IsLLVMInstructionAllowedForLib(Instruction &I, ValidationContext &ValCtx) {
  2990. if (!(ValCtx.isLibProfile ||
  2991. ValCtx.DxilMod.GetShaderModel()->IsMS() ||
  2992. ValCtx.DxilMod.GetShaderModel()->IsAS()))
  2993. return false;
  2994. switch (I.getOpcode()) {
  2995. case Instruction::InsertElement:
  2996. case Instruction::ExtractElement:
  2997. case Instruction::ShuffleVector:
  2998. return true;
  2999. case Instruction::Unreachable:
  3000. if (Instruction *Prev = I.getPrevNode()) {
  3001. if (CallInst *CI = dyn_cast<CallInst>(Prev)) {
  3002. Function *F = CI->getCalledFunction();
  3003. if (IsDxilFunction(F) &&
  3004. F->hasFnAttribute(Attribute::AttrKind::NoReturn)) {
  3005. return true;
  3006. }
  3007. }
  3008. }
  3009. return false;
  3010. default:
  3011. return false;
  3012. }
  3013. }
  3014. static void ValidateFunctionBody(Function *F, ValidationContext &ValCtx) {
  3015. bool SupportsMinPrecision =
  3016. ValCtx.DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision;
  3017. SmallVector<CallInst *, 16> gradientOps;
  3018. SmallVector<CallInst *, 16> barriers;
  3019. CallInst *setMeshOutputCounts = nullptr;
  3020. CallInst *getMeshPayload = nullptr;
  3021. CallInst *dispatchMesh = nullptr;
  3022. for (auto b = F->begin(), bend = F->end(); b != bend; ++b) {
  3023. for (auto i = b->begin(), iend = b->end(); i != iend; ++i) {
  3024. llvm::Instruction &I = *i;
  3025. if (I.hasMetadata()) {
  3026. ValidateInstructionMetadata(&I, ValCtx);
  3027. }
  3028. // Instructions must be allowed.
  3029. if (!IsLLVMInstructionAllowed(I)) {
  3030. if (!IsLLVMInstructionAllowedForLib(I, ValCtx)) {
  3031. ValCtx.EmitInstrError(&I, ValidationRule::InstrAllowed);
  3032. continue;
  3033. }
  3034. }
  3035. // Instructions marked precise may not have minprecision arguments.
  3036. if (SupportsMinPrecision) {
  3037. if (IsPrecise(I, ValCtx)) {
  3038. for (auto &O : I.operands()) {
  3039. if (IsValueMinPrec(ValCtx.DxilMod, O)) {
  3040. ValCtx.EmitInstrError(
  3041. &I, ValidationRule::InstrMinPrecisionNotPrecise);
  3042. break;
  3043. }
  3044. }
  3045. }
  3046. }
  3047. // Calls to external functions.
  3048. CallInst *CI = dyn_cast<CallInst>(&I);
  3049. if (CI) {
  3050. Function *FCalled = CI->getCalledFunction();
  3051. if (FCalled->isDeclaration()) {
  3052. // External function validation will diagnose.
  3053. if (!IsDxilFunction(FCalled)) {
  3054. continue;
  3055. }
  3056. Value *opcodeVal = CI->getOperand(0);
  3057. ConstantInt *OpcodeConst = dyn_cast<ConstantInt>(opcodeVal);
  3058. if (OpcodeConst == nullptr) {
  3059. ValCtx.EmitInstrFormatError(&I, ValidationRule::InstrOpConst,
  3060. {"Opcode", "DXIL operation"});
  3061. continue;
  3062. }
  3063. unsigned opcode = OpcodeConst->getLimitedValue();
  3064. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  3065. if (OP::IsDxilOpGradient(dxilOpcode)) {
  3066. gradientOps.push_back(CI);
  3067. }
  3068. if (dxilOpcode == DXIL::OpCode::Barrier) {
  3069. barriers.push_back(CI);
  3070. }
  3071. // External function validation will check the parameter
  3072. // list. This function will check that the call does not
  3073. // violate any rules.
  3074. if (dxilOpcode == DXIL::OpCode::SetMeshOutputCounts) {
  3075. // validate the call count of SetMeshOutputCounts
  3076. if (setMeshOutputCounts != nullptr) {
  3077. ValCtx.EmitInstrError(&I, ValidationRule::InstrMultipleSetMeshOutputCounts);
  3078. }
  3079. setMeshOutputCounts = CI;
  3080. }
  3081. if (dxilOpcode == DXIL::OpCode::GetMeshPayload) {
  3082. // validate the call count of GetMeshPayload
  3083. if (getMeshPayload != nullptr) {
  3084. ValCtx.EmitInstrError(&I, ValidationRule::InstrMultipleGetMeshPayload);
  3085. }
  3086. getMeshPayload = CI;
  3087. }
  3088. if (dxilOpcode == DXIL::OpCode::DispatchMesh) {
  3089. // validate the call count of DispatchMesh
  3090. if (dispatchMesh != nullptr) {
  3091. ValCtx.EmitInstrError(&I, ValidationRule::InstrNotOnceDispatchMesh);
  3092. }
  3093. dispatchMesh = CI;
  3094. }
  3095. }
  3096. continue;
  3097. }
  3098. for (Value *op : I.operands()) {
  3099. if (isa<UndefValue>(op)) {
  3100. bool legalUndef = isa<PHINode>(&I);
  3101. if (InsertElementInst *InsertInst = dyn_cast<InsertElementInst>(&I)) {
  3102. legalUndef = op == I.getOperand(0);
  3103. }
  3104. if (ShuffleVectorInst *Shuf = dyn_cast<ShuffleVectorInst>(&I)) {
  3105. legalUndef = op == I.getOperand(1);
  3106. }
  3107. if (!legalUndef)
  3108. ValCtx.EmitInstrError(&I,
  3109. ValidationRule::InstrNoReadingUninitialized);
  3110. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(op)) {
  3111. for (Value *opCE : CE->operands()) {
  3112. if (isa<UndefValue>(opCE)) {
  3113. ValCtx.EmitInstrError(
  3114. &I, ValidationRule::InstrNoReadingUninitialized);
  3115. }
  3116. }
  3117. }
  3118. if (IntegerType *IT = dyn_cast<IntegerType>(op->getType())) {
  3119. if (IT->getBitWidth() == 8) {
  3120. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  3121. }
  3122. }
  3123. }
  3124. Type *Ty = I.getType();
  3125. if (isa<PointerType>(Ty))
  3126. Ty = Ty->getPointerElementType();
  3127. while (isa<ArrayType>(Ty))
  3128. Ty = Ty->getArrayElementType();
  3129. if (IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
  3130. if (IT->getBitWidth() == 8) {
  3131. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  3132. }
  3133. }
  3134. unsigned opcode = I.getOpcode();
  3135. switch (opcode) {
  3136. case Instruction::Alloca: {
  3137. AllocaInst *AI = cast<AllocaInst>(&I);
  3138. // TODO: validate address space and alignment
  3139. Type *Ty = AI->getAllocatedType();
  3140. if (!ValidateType(Ty, ValCtx)) {
  3141. continue;
  3142. }
  3143. } break;
  3144. case Instruction::ExtractValue: {
  3145. ExtractValueInst *EV = cast<ExtractValueInst>(&I);
  3146. Type *Ty = EV->getAggregateOperand()->getType();
  3147. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3148. Value *Agg = EV->getAggregateOperand();
  3149. if (!isa<AtomicCmpXchgInst>(Agg) &&
  3150. !IsDxilBuiltinStructType(ST, ValCtx.DxilMod.GetOP())) {
  3151. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  3152. }
  3153. } else {
  3154. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  3155. }
  3156. } break;
  3157. case Instruction::Load: {
  3158. Type *Ty = I.getType();
  3159. if (!ValidateType(Ty, ValCtx)) {
  3160. continue;
  3161. }
  3162. } break;
  3163. case Instruction::Store: {
  3164. StoreInst *SI = cast<StoreInst>(&I);
  3165. Type *Ty = SI->getValueOperand()->getType();
  3166. if (!ValidateType(Ty, ValCtx)) {
  3167. continue;
  3168. }
  3169. } break;
  3170. case Instruction::GetElementPtr: {
  3171. Type *Ty = I.getType()->getPointerElementType();
  3172. if (!ValidateType(Ty, ValCtx)) {
  3173. continue;
  3174. }
  3175. GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
  3176. bool allImmIndex = true;
  3177. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  3178. if (!isa<ConstantInt>(Idx)) {
  3179. allImmIndex = false;
  3180. break;
  3181. }
  3182. }
  3183. if (allImmIndex) {
  3184. const DataLayout &DL = ValCtx.DL;
  3185. Value *Ptr = GEP->getPointerOperand();
  3186. unsigned size =
  3187. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  3188. unsigned valSize = DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  3189. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  3190. unsigned offset =
  3191. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  3192. if ((offset + valSize) > size) {
  3193. ValCtx.EmitInstrError(GEP, ValidationRule::InstrInBoundsAccess);
  3194. }
  3195. }
  3196. } break;
  3197. case Instruction::SDiv: {
  3198. BinaryOperator *BO = cast<BinaryOperator>(&I);
  3199. Value *V = BO->getOperand(1);
  3200. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  3201. if (imm->getValue().getLimitedValue() == 0) {
  3202. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoIDivByZero);
  3203. }
  3204. }
  3205. } break;
  3206. case Instruction::UDiv: {
  3207. BinaryOperator *BO = cast<BinaryOperator>(&I);
  3208. Value *V = BO->getOperand(1);
  3209. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  3210. if (imm->getValue().getLimitedValue() == 0) {
  3211. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoUDivByZero);
  3212. }
  3213. }
  3214. } break;
  3215. case Instruction::AddrSpaceCast: {
  3216. AddrSpaceCastInst *Cast = cast<AddrSpaceCastInst>(&I);
  3217. unsigned ToAddrSpace = Cast->getType()->getPointerAddressSpace();
  3218. unsigned FromAddrSpace = Cast->getOperand(0)->getType()->getPointerAddressSpace();
  3219. if (ToAddrSpace != DXIL::kGenericPointerAddrSpace &&
  3220. FromAddrSpace != DXIL::kGenericPointerAddrSpace) {
  3221. ValCtx.EmitInstrError(Cast, ValidationRule::InstrNoGenericPtrAddrSpaceCast);
  3222. }
  3223. } break;
  3224. case Instruction::BitCast: {
  3225. BitCastInst *Cast = cast<BitCastInst>(&I);
  3226. Type *FromTy = Cast->getOperand(0)->getType();
  3227. Type *ToTy = Cast->getType();
  3228. if (isa<PointerType>(FromTy)) {
  3229. FromTy = FromTy->getPointerElementType();
  3230. ToTy = ToTy->getPointerElementType();
  3231. unsigned FromSize = ValCtx.DL.getTypeAllocSize(FromTy);
  3232. unsigned ToSize = ValCtx.DL.getTypeAllocSize(ToTy);
  3233. if (FromSize != ToSize) {
  3234. ValCtx.EmitInstrError(Cast, ValidationRule::InstrPtrBitCast);
  3235. continue;
  3236. }
  3237. while (isa<ArrayType>(FromTy)) {
  3238. FromTy = FromTy->getArrayElementType();
  3239. }
  3240. while (isa<ArrayType>(ToTy)) {
  3241. ToTy = ToTy->getArrayElementType();
  3242. }
  3243. }
  3244. if ((isa<StructType>(FromTy) || isa<StructType>(ToTy)) && !ValCtx.isLibProfile) {
  3245. ValCtx.EmitInstrError(Cast, ValidationRule::InstrStructBitCast);
  3246. continue;
  3247. }
  3248. bool IsMinPrecisionTy =
  3249. (ValCtx.DL.getTypeStoreSize(FromTy) < 4 ||
  3250. ValCtx.DL.getTypeStoreSize(ToTy) < 4) &&
  3251. ValCtx.DxilMod.GetUseMinPrecision();
  3252. if (IsMinPrecisionTy) {
  3253. ValCtx.EmitInstrError(Cast, ValidationRule::InstrMinPrecisonBitCast);
  3254. }
  3255. } break;
  3256. }
  3257. if (PointerType *PT = dyn_cast<PointerType>(I.getType())) {
  3258. if (PT->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  3259. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  3260. Value *Ptr = GEP->getPointerOperand();
  3261. // Allow inner constant GEP
  3262. if (isa<ConstantExpr>(Ptr) && isa<GEPOperator>(Ptr))
  3263. Ptr = cast<GEPOperator>(Ptr)->getPointerOperand();
  3264. if (!isa<GlobalVariable>(Ptr)) {
  3265. ValCtx.EmitInstrError(
  3266. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  3267. }
  3268. } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(&I)) {
  3269. Value *Ptr = BCI->getOperand(0);
  3270. // Allow inner constant GEP
  3271. if (isa<ConstantExpr>(Ptr) && isa<GEPOperator>(Ptr))
  3272. Ptr = cast<GEPOperator>(Ptr)->getPointerOperand();
  3273. if (!isa<GetElementPtrInst>(Ptr) && !isa<GlobalVariable>(Ptr)) {
  3274. ValCtx.EmitInstrError(
  3275. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  3276. }
  3277. } else {
  3278. ValCtx.EmitInstrError(
  3279. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  3280. }
  3281. }
  3282. }
  3283. }
  3284. ValidateControlFlowHint(*b, ValCtx);
  3285. }
  3286. ValidateMsIntrinsics(F, ValCtx, setMeshOutputCounts, getMeshPayload);
  3287. ValidateAsIntrinsics(F, ValCtx, dispatchMesh);
  3288. }
  3289. static void ValidateFunction(Function &F, ValidationContext &ValCtx) {
  3290. if (F.isDeclaration()) {
  3291. ValidateExternalFunction(&F, ValCtx);
  3292. if (F.isIntrinsic() || IsDxilFunction(&F))
  3293. return;
  3294. } else {
  3295. DXIL::ShaderKind shaderKind = DXIL::ShaderKind::Library;
  3296. bool isShader = ValCtx.DxilMod.HasDxilFunctionProps(&F);
  3297. unsigned numUDTShaderArgs = 0;
  3298. if (isShader) {
  3299. shaderKind = ValCtx.DxilMod.GetDxilFunctionProps(&F).shaderKind;
  3300. switch (shaderKind) {
  3301. case DXIL::ShaderKind::AnyHit:
  3302. case DXIL::ShaderKind::ClosestHit:
  3303. numUDTShaderArgs = 2;
  3304. break;
  3305. case DXIL::ShaderKind::Miss:
  3306. case DXIL::ShaderKind::Callable:
  3307. numUDTShaderArgs = 1;
  3308. break;
  3309. default:
  3310. break;
  3311. }
  3312. } else {
  3313. isShader = ValCtx.DxilMod.IsPatchConstantShader(&F);
  3314. }
  3315. // Entry function should not have parameter.
  3316. if (isShader && 0 == numUDTShaderArgs && !F.arg_empty())
  3317. ValCtx.EmitFormatError(ValidationRule::FlowFunctionCall, { F.getName() });
  3318. // Shader functions should return void.
  3319. if (isShader && !F.getReturnType()->isVoidTy())
  3320. ValCtx.EmitFormatError(ValidationRule::DeclShaderReturnVoid, { F.getName() });
  3321. auto ArgFormatError = [&](Argument &arg, ValidationRule rule) {
  3322. if (arg.hasName())
  3323. ValCtx.EmitFormatError(rule, { arg.getName().str(), F.getName() });
  3324. else
  3325. ValCtx.EmitFormatError(rule, { std::to_string(arg.getArgNo()), F.getName() });
  3326. };
  3327. // Validate parameter type.
  3328. unsigned numArgs = 0;
  3329. for (auto &arg : F.args()) {
  3330. Type *argTy = arg.getType();
  3331. if (argTy->isPointerTy())
  3332. argTy = argTy->getPointerElementType();
  3333. numArgs++;
  3334. if (numUDTShaderArgs) {
  3335. if (arg.getArgNo() >= numUDTShaderArgs) {
  3336. ArgFormatError(arg, ValidationRule::DeclExtraArgs);
  3337. } else if (!argTy->isStructTy()) {
  3338. ArgFormatError(arg,
  3339. shaderKind == DXIL::ShaderKind::Callable
  3340. ? ValidationRule::DeclParamStruct
  3341. : arg.getArgNo() == 0 ? ValidationRule::DeclPayloadStruct
  3342. : ValidationRule::DeclAttrStruct);
  3343. }
  3344. continue;
  3345. }
  3346. while (argTy->isArrayTy()) {
  3347. argTy = argTy->getArrayElementType();
  3348. }
  3349. if (argTy->isStructTy() && !ValCtx.isLibProfile) {
  3350. ArgFormatError(arg, ValidationRule::DeclFnFlattenParam);
  3351. break;
  3352. }
  3353. }
  3354. if (numArgs < numUDTShaderArgs) {
  3355. StringRef argType[2] = { shaderKind == DXIL::ShaderKind::Callable ?
  3356. "params" : "payload", "attributes" };
  3357. for (unsigned i = numArgs; i < numUDTShaderArgs; i++) {
  3358. ValCtx.EmitFormatError(ValidationRule::DeclShaderMissingArg,
  3359. { ShaderModel::GetKindName(shaderKind), F.getName(), argType[i] });
  3360. }
  3361. }
  3362. ValidateFunctionBody(&F, ValCtx);
  3363. }
  3364. // function params & return type must not contain resources
  3365. if (dxilutil::ContainsHLSLObjectType(F.getReturnType())) {
  3366. ValCtx.EmitGlobalValueError(&F, ValidationRule::DeclResourceInFnSig);
  3367. return;
  3368. }
  3369. for (auto &Arg : F.args()) {
  3370. if (dxilutil::ContainsHLSLObjectType(Arg.getType())) {
  3371. ValCtx.EmitGlobalValueError(&F, ValidationRule::DeclResourceInFnSig);
  3372. return;
  3373. }
  3374. }
  3375. // TODO: Remove attribute for lib?
  3376. if (!ValCtx.isLibProfile)
  3377. ValidateFunctionAttribute(&F, ValCtx);
  3378. if (F.hasMetadata()) {
  3379. ValidateFunctionMetadata(&F, ValCtx);
  3380. }
  3381. }
  3382. static void ValidateGlobalVariable(GlobalVariable &GV,
  3383. ValidationContext &ValCtx) {
  3384. bool isInternalGV =
  3385. dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV);
  3386. if (ValCtx.isLibProfile) {
  3387. auto isCBufferGlobal = [&](const std::vector<std::unique_ptr<DxilCBuffer>> &ResTab) -> bool {
  3388. for (auto &Res : ResTab)
  3389. if (Res->GetGlobalSymbol() == &GV)
  3390. return true;
  3391. return false;
  3392. };
  3393. auto isResourceGlobal = [&](const std::vector<std::unique_ptr<DxilResource>> &ResTab) -> bool {
  3394. for (auto &Res : ResTab)
  3395. if (Res->GetGlobalSymbol() == &GV)
  3396. return true;
  3397. return false;
  3398. };
  3399. auto isSamplerGlobal = [&](const std::vector<std::unique_ptr<DxilSampler>> &ResTab) -> bool {
  3400. for (auto &Res : ResTab)
  3401. if (Res->GetGlobalSymbol() == &GV)
  3402. return true;
  3403. return false;
  3404. };
  3405. bool isRes = isCBufferGlobal(ValCtx.DxilMod.GetCBuffers());
  3406. isRes |= isResourceGlobal(ValCtx.DxilMod.GetUAVs());
  3407. isRes |= isResourceGlobal(ValCtx.DxilMod.GetSRVs());
  3408. isRes |= isSamplerGlobal(ValCtx.DxilMod.GetSamplers());
  3409. isInternalGV |= isRes;
  3410. }
  3411. if (!isInternalGV) {
  3412. if (!GV.user_empty()) {
  3413. bool hasInstructionUser = false;
  3414. for (User *U : GV.users()) {
  3415. if (isa<Instruction>(U)) {
  3416. hasInstructionUser = true;
  3417. break;
  3418. }
  3419. }
  3420. // External GV should not have instruction user.
  3421. if (hasInstructionUser) {
  3422. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclNotUsedExternal);
  3423. }
  3424. }
  3425. // Must have metadata description for each variable.
  3426. } else {
  3427. // Internal GV must have user.
  3428. if (GV.user_empty()) {
  3429. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclUsedInternal);
  3430. }
  3431. // Validate type for internal globals.
  3432. if (dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV)) {
  3433. Type *Ty = GV.getType()->getPointerElementType();
  3434. ValidateType(Ty, ValCtx);
  3435. }
  3436. }
  3437. }
  3438. static void CollectFixAddressAccess(Value *V,
  3439. std::vector<StoreInst *> &fixAddrTGSMList) {
  3440. for (User *U : V->users()) {
  3441. if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3442. if (isa<ConstantExpr>(GEP) || GEP->hasAllConstantIndices()) {
  3443. CollectFixAddressAccess(GEP, fixAddrTGSMList);
  3444. }
  3445. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3446. fixAddrTGSMList.emplace_back(SI);
  3447. }
  3448. }
  3449. }
  3450. static bool IsDivergent(Value *V) {
  3451. // TODO: return correct result.
  3452. return false;
  3453. }
  3454. static void ValidateTGSMRaceCondition(std::vector<StoreInst *> &fixAddrTGSMList,
  3455. ValidationContext &ValCtx) {
  3456. std::unordered_set<Function *> fixAddrTGSMFuncSet;
  3457. for (StoreInst *I : fixAddrTGSMList) {
  3458. BasicBlock *BB = I->getParent();
  3459. fixAddrTGSMFuncSet.insert(BB->getParent());
  3460. }
  3461. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  3462. if (F.isDeclaration() || !fixAddrTGSMFuncSet.count(&F))
  3463. continue;
  3464. PostDominatorTree PDT;
  3465. PDT.runOnFunction(F);
  3466. BasicBlock *Entry = &F.getEntryBlock();
  3467. for (StoreInst *SI : fixAddrTGSMList) {
  3468. BasicBlock *BB = SI->getParent();
  3469. if (BB->getParent() == &F) {
  3470. if (PDT.dominates(BB, Entry)) {
  3471. if (IsDivergent(SI->getValueOperand()))
  3472. ValCtx.EmitInstrError(SI, ValidationRule::InstrTGSMRaceCond);
  3473. }
  3474. }
  3475. }
  3476. }
  3477. }
  3478. static void ValidateGlobalVariables(ValidationContext &ValCtx) {
  3479. DxilModule &M = ValCtx.DxilMod;
  3480. unsigned TGSMSize = 0;
  3481. std::vector<StoreInst*> fixAddrTGSMList;
  3482. const DataLayout &DL = M.GetModule()->getDataLayout();
  3483. for (GlobalVariable &GV : M.GetModule()->globals()) {
  3484. ValidateGlobalVariable(GV, ValCtx);
  3485. if (GV.getType()->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  3486. TGSMSize += DL.getTypeAllocSize(GV.getType()->getElementType());
  3487. CollectFixAddressAccess(&GV, fixAddrTGSMList);
  3488. }
  3489. }
  3490. if (M.GetShaderModel()->IsMS()) {
  3491. if (TGSMSize > DXIL::kMaxMSSMSize) {
  3492. ValCtx.EmitFormatError(ValidationRule::SmMaxMSSMSize,
  3493. { std::to_string(TGSMSize),
  3494. std::to_string(DXIL::kMaxMSSMSize) });
  3495. }
  3496. } else if (TGSMSize > DXIL::kMaxTGSMSize) {
  3497. ValCtx.EmitFormatError(ValidationRule::SmMaxTGSMSize,
  3498. { std::to_string(TGSMSize),
  3499. std::to_string(DXIL::kMaxTGSMSize) });
  3500. }
  3501. if (!fixAddrTGSMList.empty()) {
  3502. ValidateTGSMRaceCondition(fixAddrTGSMList, ValCtx);
  3503. }
  3504. }
  3505. static void ValidateValidatorVersion(ValidationContext &ValCtx) {
  3506. Module *pModule = &ValCtx.M;
  3507. NamedMDNode *pNode = pModule->getNamedMetadata("dx.valver");
  3508. if (pNode == nullptr) {
  3509. return;
  3510. }
  3511. if (pNode->getNumOperands() == 1) {
  3512. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  3513. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  3514. uint64_t majorVer, minorVer;
  3515. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  3516. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  3517. unsigned curMajor, curMinor;
  3518. GetValidationVersion(&curMajor, &curMinor);
  3519. // This will need to be updated as major/minor versions evolve,
  3520. // depending on the degree of compat across versions.
  3521. if (majorVer == curMajor && minorVer <= curMinor) {
  3522. return;
  3523. }
  3524. }
  3525. }
  3526. }
  3527. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  3528. }
  3529. static void ValidateDxilVersion(ValidationContext &ValCtx) {
  3530. Module *pModule = &ValCtx.M;
  3531. NamedMDNode *pNode = pModule->getNamedMetadata("dx.version");
  3532. if (pNode && pNode->getNumOperands() == 1) {
  3533. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  3534. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  3535. uint64_t majorVer, minorVer;
  3536. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  3537. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  3538. // This will need to be updated as dxil major/minor versions evolve,
  3539. // depending on the degree of compat across versions.
  3540. if ((majorVer == 1 && minorVer <= DXIL::kDxilMinor) &&
  3541. (majorVer == ValCtx.m_DxilMajor && minorVer == ValCtx.m_DxilMinor)) {
  3542. return;
  3543. }
  3544. }
  3545. }
  3546. }
  3547. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  3548. }
  3549. static void ValidateTypeAnnotation(ValidationContext &ValCtx) {
  3550. if (ValCtx.m_DxilMajor == 1 && ValCtx.m_DxilMinor >= 2) {
  3551. Module *pModule = &ValCtx.M;
  3552. NamedMDNode *TA = pModule->getNamedMetadata("dx.typeAnnotations");
  3553. if (TA == nullptr)
  3554. return;
  3555. for (unsigned i = 0, end = TA->getNumOperands(); i < end; ++i) {
  3556. MDTuple *TANode = dyn_cast<MDTuple>(TA->getOperand(i));
  3557. if (TANode->getNumOperands() < 3) {
  3558. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  3559. return;
  3560. }
  3561. ConstantInt *tag = mdconst::extract<ConstantInt>(TANode->getOperand(0));
  3562. uint64_t tagValue = tag->getZExtValue();
  3563. if (tagValue != DxilMDHelper::kDxilTypeSystemStructTag &&
  3564. tagValue != DxilMDHelper::kDxilTypeSystemFunctionTag) {
  3565. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  3566. return;
  3567. }
  3568. }
  3569. }
  3570. }
  3571. static void ValidateBitcode(ValidationContext &ValCtx) {
  3572. if (llvm::verifyModule(ValCtx.M, &ValCtx.DiagStream())) {
  3573. ValCtx.EmitError(ValidationRule::BitcodeValid);
  3574. }
  3575. }
  3576. static void ValidateMetadata(ValidationContext &ValCtx) {
  3577. Module *pModule = &ValCtx.M;
  3578. const std::string &target = pModule->getTargetTriple();
  3579. if (target != "dxil-ms-dx") {
  3580. ValCtx.EmitFormatError(ValidationRule::MetaTarget, {target});
  3581. }
  3582. // The llvm.dbg.(cu/contents/defines/mainFileName/arg) named metadata nodes
  3583. // are only available in debug modules, not in the validated ones.
  3584. // llvm.bitsets is also disallowed.
  3585. //
  3586. // These are verified in lib/IR/Verifier.cpp.
  3587. StringMap<bool> llvmNamedMeta;
  3588. llvmNamedMeta["llvm.ident"];
  3589. llvmNamedMeta["llvm.module.flags"];
  3590. for (auto &NamedMetaNode : pModule->named_metadata()) {
  3591. if (!DxilModule::IsKnownNamedMetaData(NamedMetaNode)) {
  3592. StringRef name = NamedMetaNode.getName();
  3593. if (!name.startswith_lower("llvm.")) {
  3594. ValCtx.EmitFormatError(ValidationRule::MetaKnown, {name.str()});
  3595. }
  3596. else {
  3597. if (llvmNamedMeta.count(name) == 0) {
  3598. ValCtx.EmitFormatError(ValidationRule::MetaKnown,
  3599. {name.str()});
  3600. }
  3601. }
  3602. }
  3603. }
  3604. const hlsl::ShaderModel *SM = ValCtx.DxilMod.GetShaderModel();
  3605. if (!SM->IsValidForDxil()) {
  3606. ValCtx.EmitFormatError(ValidationRule::SmName,
  3607. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  3608. }
  3609. if (SM->GetMajor() == 6) {
  3610. // Make sure DxilVersion matches the shader model.
  3611. unsigned SMDxilMajor, SMDxilMinor;
  3612. SM->GetDxilVersion(SMDxilMajor, SMDxilMinor);
  3613. if (ValCtx.m_DxilMajor != SMDxilMajor || ValCtx.m_DxilMinor != SMDxilMinor) {
  3614. ValCtx.EmitFormatError(ValidationRule::SmDxilVersion,
  3615. {std::to_string(SMDxilMajor),
  3616. std::to_string(SMDxilMinor)});
  3617. }
  3618. }
  3619. ValidateDxilVersion(ValCtx);
  3620. ValidateValidatorVersion(ValCtx);
  3621. ValidateTypeAnnotation(ValCtx);
  3622. }
  3623. static void ValidateResourceOverlap(
  3624. hlsl::DxilResourceBase &res,
  3625. SpacesAllocator<unsigned, DxilResourceBase> &spaceAllocator,
  3626. ValidationContext &ValCtx) {
  3627. unsigned base = res.GetLowerBound();
  3628. if (ValCtx.isLibProfile && !res.IsAllocated()) {
  3629. // Skip unallocated resource for library.
  3630. return;
  3631. }
  3632. unsigned size = res.GetRangeSize();
  3633. unsigned space = res.GetSpaceID();
  3634. auto &allocator = spaceAllocator.Get(space);
  3635. unsigned end = base + size - 1;
  3636. // unbounded
  3637. if (end < base)
  3638. end = size;
  3639. const DxilResourceBase *conflictRes = allocator.Insert(&res, base, end);
  3640. if (conflictRes) {
  3641. ValCtx.EmitFormatError(
  3642. ValidationRule::SmResourceRangeOverlap,
  3643. {res.GetGlobalName(), std::to_string(base),
  3644. std::to_string(size),
  3645. std::to_string(conflictRes->GetLowerBound()),
  3646. std::to_string(conflictRes->GetRangeSize()),
  3647. std::to_string(space)});
  3648. }
  3649. }
  3650. static void ValidateResource(hlsl::DxilResource &res,
  3651. ValidationContext &ValCtx) {
  3652. switch (res.GetKind()) {
  3653. case DXIL::ResourceKind::RawBuffer:
  3654. case DXIL::ResourceKind::TypedBuffer:
  3655. case DXIL::ResourceKind::TBuffer:
  3656. case DXIL::ResourceKind::StructuredBuffer:
  3657. case DXIL::ResourceKind::StructuredBufferWithCounter:
  3658. case DXIL::ResourceKind::Texture1D:
  3659. case DXIL::ResourceKind::Texture1DArray:
  3660. case DXIL::ResourceKind::Texture2D:
  3661. case DXIL::ResourceKind::Texture2DArray:
  3662. case DXIL::ResourceKind::Texture3D:
  3663. case DXIL::ResourceKind::TextureCube:
  3664. case DXIL::ResourceKind::TextureCubeArray:
  3665. if (res.GetSampleCount() > 0) {
  3666. ValCtx.EmitResourceError(&res, ValidationRule::SmSampleCountOnlyOn2DMS);
  3667. }
  3668. break;
  3669. case DXIL::ResourceKind::Texture2DMS:
  3670. case DXIL::ResourceKind::Texture2DMSArray:
  3671. break;
  3672. case DXIL::ResourceKind::RTAccelerationStructure:
  3673. // TODO: check profile.
  3674. break;
  3675. case DXIL::ResourceKind::FeedbackTexture2D:
  3676. case DXIL::ResourceKind::FeedbackTexture2DArray:
  3677. if (res.GetSamplerFeedbackType() >= DXIL::SamplerFeedbackType::LastEntry)
  3678. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidSamplerFeedbackType);
  3679. break;
  3680. default:
  3681. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceKind);
  3682. break;
  3683. }
  3684. switch (res.GetCompType().GetKind()) {
  3685. case DXIL::ComponentType::F32:
  3686. case DXIL::ComponentType::SNormF32:
  3687. case DXIL::ComponentType::UNormF32:
  3688. case DXIL::ComponentType::F64:
  3689. case DXIL::ComponentType::I32:
  3690. case DXIL::ComponentType::I64:
  3691. case DXIL::ComponentType::U32:
  3692. case DXIL::ComponentType::U64:
  3693. case DXIL::ComponentType::F16:
  3694. case DXIL::ComponentType::I16:
  3695. case DXIL::ComponentType::U16:
  3696. break;
  3697. default:
  3698. if (!res.IsStructuredBuffer() && !res.IsRawBuffer() && !res.IsFeedbackTexture())
  3699. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceCompType);
  3700. break;
  3701. }
  3702. if (res.IsStructuredBuffer()) {
  3703. unsigned stride = res.GetElementStride();
  3704. bool alignedTo4Bytes = (stride & 3) == 0;
  3705. if (!alignedTo4Bytes && ValCtx.M.GetDxilModule().GetUseMinPrecision()) {
  3706. ValCtx.EmitResourceFormatError(
  3707. &res, ValidationRule::MetaStructBufAlignment,
  3708. {std::to_string(4), std::to_string(stride)});
  3709. }
  3710. if (stride > DXIL::kMaxStructBufferStride) {
  3711. ValCtx.EmitResourceFormatError(
  3712. &res, ValidationRule::MetaStructBufAlignmentOutOfBound,
  3713. {std::to_string(DXIL::kMaxStructBufferStride),
  3714. std::to_string(stride)});
  3715. }
  3716. }
  3717. if (res.IsAnyTexture() || res.IsTypedBuffer()) {
  3718. Type *RetTy = res.GetRetType();
  3719. unsigned size = ValCtx.DxilMod.GetModule()->getDataLayout().getTypeAllocSize(RetTy);
  3720. if (size > 4*4) {
  3721. ValCtx.EmitResourceError(&res, ValidationRule::MetaTextureType);
  3722. }
  3723. }
  3724. }
  3725. static void
  3726. CollectCBufferRanges(DxilStructAnnotation *annotation,
  3727. SpanAllocator<unsigned, DxilFieldAnnotation> &constAllocator,
  3728. unsigned base, DxilTypeSystem &typeSys, StringRef cbName,
  3729. ValidationContext &ValCtx) {
  3730. DXASSERT(((base + 15) & ~(0xf)) == base, "otherwise, base for struct is not aligned");
  3731. unsigned cbSize = annotation->GetCBufferSize();
  3732. const StructType *ST = annotation->GetStructType();
  3733. for (int i = annotation->GetNumFields() - 1; i >= 0; i--) {
  3734. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  3735. Type *EltTy = ST->getElementType(i);
  3736. unsigned offset = fieldAnnotation.GetCBufferOffset();
  3737. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  3738. fieldAnnotation, EltTy, typeSys);
  3739. bool bOutOfBound = false;
  3740. if (!EltTy->isAggregateType()) {
  3741. bOutOfBound = (offset + EltSize) > cbSize;
  3742. if (!bOutOfBound) {
  3743. if (constAllocator.Insert(&fieldAnnotation, base + offset,
  3744. base + offset + EltSize - 1)) {
  3745. ValCtx.EmitFormatError(
  3746. ValidationRule::SmCBufferOffsetOverlap,
  3747. {cbName, std::to_string(base + offset)});
  3748. }
  3749. }
  3750. } else if (isa<ArrayType>(EltTy)) {
  3751. if (((offset + 15) & ~(0xf)) != offset) {
  3752. ValCtx.EmitFormatError(
  3753. ValidationRule::SmCBufferArrayOffsetAlignment,
  3754. {cbName, std::to_string(offset)});
  3755. continue;
  3756. }
  3757. unsigned arrayCount = 1;
  3758. while (isa<ArrayType>(EltTy)) {
  3759. arrayCount *= EltTy->getArrayNumElements();
  3760. EltTy = EltTy->getArrayElementType();
  3761. }
  3762. DxilStructAnnotation *EltAnnotation = nullptr;
  3763. if (StructType *EltST = dyn_cast<StructType>(EltTy))
  3764. EltAnnotation = typeSys.GetStructAnnotation(EltST);
  3765. unsigned alignedEltSize = ((EltSize + 15) & ~(0xf));
  3766. unsigned arraySize = ((arrayCount - 1) * alignedEltSize) + EltSize;
  3767. bOutOfBound = (offset + arraySize) > cbSize;
  3768. if (!bOutOfBound) {
  3769. // If we didn't care about gaps where elements could be placed with user offsets,
  3770. // we could: recurse once if EltAnnotation, then allocate the rest if arrayCount > 1
  3771. unsigned arrayBase = base + offset;
  3772. if (!EltAnnotation) {
  3773. if (EltSize > 0 && nullptr != constAllocator.Insert(
  3774. &fieldAnnotation, arrayBase, arrayBase + arraySize - 1)) {
  3775. ValCtx.EmitFormatError(
  3776. ValidationRule::SmCBufferOffsetOverlap,
  3777. {cbName, std::to_string(arrayBase)});
  3778. }
  3779. } else {
  3780. for (unsigned idx = 0; idx < arrayCount; idx++) {
  3781. CollectCBufferRanges(EltAnnotation, constAllocator,
  3782. arrayBase, typeSys, cbName, ValCtx);
  3783. arrayBase += alignedEltSize;
  3784. }
  3785. }
  3786. }
  3787. } else {
  3788. StructType *EltST = cast<StructType>(EltTy);
  3789. unsigned structBase = base + offset;
  3790. bOutOfBound = (offset + EltSize) > cbSize;
  3791. if (!bOutOfBound) {
  3792. if (DxilStructAnnotation *EltAnnotation = typeSys.GetStructAnnotation(EltST)) {
  3793. CollectCBufferRanges(EltAnnotation, constAllocator,
  3794. structBase, typeSys, cbName, ValCtx);
  3795. } else {
  3796. if (EltSize > 0 && nullptr != constAllocator.Insert(
  3797. &fieldAnnotation, structBase, structBase + EltSize - 1)) {
  3798. ValCtx.EmitFormatError(
  3799. ValidationRule::SmCBufferOffsetOverlap,
  3800. {cbName, std::to_string(structBase)});
  3801. }
  3802. }
  3803. }
  3804. }
  3805. if (bOutOfBound) {
  3806. ValCtx.EmitFormatError(ValidationRule::SmCBufferElementOverflow,
  3807. {cbName, std::to_string(base + offset)});
  3808. }
  3809. }
  3810. }
  3811. static void ValidateCBuffer(DxilCBuffer &cb, ValidationContext &ValCtx) {
  3812. Type *Ty = cb.GetGlobalSymbol()->getType()->getPointerElementType();
  3813. if (cb.GetRangeSize() != 1) {
  3814. Ty = Ty->getArrayElementType();
  3815. }
  3816. if (!isa<StructType>(Ty)) {
  3817. ValCtx.EmitResourceError(&cb,
  3818. ValidationRule::SmCBufferTemplateTypeMustBeStruct);
  3819. return;
  3820. }
  3821. StructType *ST = cast<StructType>(Ty);
  3822. DxilTypeSystem &typeSys = ValCtx.DxilMod.GetTypeSystem();
  3823. DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST);
  3824. if (!annotation)
  3825. return;
  3826. // Collect constant ranges.
  3827. std::vector<std::pair<unsigned, unsigned>> constRanges;
  3828. SpanAllocator<unsigned, DxilFieldAnnotation> constAllocator(0,
  3829. // 4096 * 16 bytes.
  3830. DXIL::kMaxCBufferSize << 4);
  3831. CollectCBufferRanges(annotation, constAllocator,
  3832. 0, typeSys,
  3833. cb.GetGlobalName(), ValCtx);
  3834. }
  3835. static void ValidateResources(ValidationContext &ValCtx) {
  3836. const vector<unique_ptr<DxilResource>> &uavs = ValCtx.DxilMod.GetUAVs();
  3837. SpacesAllocator<unsigned, DxilResourceBase> uavAllocator;
  3838. for (auto &uav : uavs) {
  3839. if (uav->IsROV()) {
  3840. if (!ValCtx.DxilMod.GetShaderModel()->IsPS() && !ValCtx.isLibProfile) {
  3841. ValCtx.EmitResourceError(uav.get(), ValidationRule::SmROVOnlyInPS);
  3842. }
  3843. }
  3844. switch (uav->GetKind()) {
  3845. case DXIL::ResourceKind::Texture2DMS:
  3846. case DXIL::ResourceKind::Texture2DMSArray:
  3847. case DXIL::ResourceKind::TextureCube:
  3848. case DXIL::ResourceKind::TextureCubeArray:
  3849. ValCtx.EmitResourceError(uav.get(),
  3850. ValidationRule::SmInvalidTextureKindOnUAV);
  3851. break;
  3852. default:
  3853. break;
  3854. }
  3855. if (uav->HasCounter() && !uav->IsStructuredBuffer()) {
  3856. ValCtx.EmitResourceError(uav.get(),
  3857. ValidationRule::SmCounterOnlyOnStructBuf);
  3858. }
  3859. if (uav->HasCounter() && uav->IsGloballyCoherent())
  3860. ValCtx.EmitResourceError(uav.get(),
  3861. ValidationRule::MetaGlcNotOnAppendConsume);
  3862. ValidateResource(*uav, ValCtx);
  3863. ValidateResourceOverlap(*uav, uavAllocator, ValCtx);
  3864. }
  3865. SpacesAllocator<unsigned, DxilResourceBase> srvAllocator;
  3866. const vector<unique_ptr<DxilResource>> &srvs = ValCtx.DxilMod.GetSRVs();
  3867. for (auto &srv : srvs) {
  3868. ValidateResource(*srv, ValCtx);
  3869. ValidateResourceOverlap(*srv, srvAllocator, ValCtx);
  3870. }
  3871. hlsl::DxilResourceBase *pNonDense;
  3872. if (!AreDxilResourcesDense(&ValCtx.M, &pNonDense)) {
  3873. ValCtx.EmitResourceError(pNonDense, ValidationRule::MetaDenseResIDs);
  3874. }
  3875. SpacesAllocator<unsigned, DxilResourceBase> samplerAllocator;
  3876. for (auto &sampler : ValCtx.DxilMod.GetSamplers()) {
  3877. if (sampler->GetSamplerKind() == DXIL::SamplerKind::Invalid) {
  3878. ValCtx.EmitResourceError(sampler.get(),
  3879. ValidationRule::MetaValidSamplerMode);
  3880. }
  3881. ValidateResourceOverlap(*sampler, samplerAllocator, ValCtx);
  3882. }
  3883. SpacesAllocator<unsigned, DxilResourceBase> cbufferAllocator;
  3884. for (auto &cbuffer : ValCtx.DxilMod.GetCBuffers()) {
  3885. ValidateCBuffer(*cbuffer, ValCtx);
  3886. ValidateResourceOverlap(*cbuffer, cbufferAllocator, ValCtx);
  3887. }
  3888. }
  3889. static void ValidateShaderFlags(ValidationContext &ValCtx) {
  3890. // TODO: validate flags foreach entry.
  3891. if (ValCtx.isLibProfile)
  3892. return;
  3893. ShaderFlags calcFlags;
  3894. ValCtx.DxilMod.CollectShaderFlagsForModule(calcFlags);
  3895. const uint64_t mask = ShaderFlags::GetShaderFlagsRawForCollection();
  3896. uint64_t declaredFlagsRaw = ValCtx.DxilMod.m_ShaderFlags.GetShaderFlagsRaw();
  3897. uint64_t calcFlagsRaw = calcFlags.GetShaderFlagsRaw();
  3898. declaredFlagsRaw &= mask;
  3899. calcFlagsRaw &= mask;
  3900. if (declaredFlagsRaw == calcFlagsRaw) {
  3901. return;
  3902. }
  3903. ValCtx.EmitError(ValidationRule::MetaFlagsUsage);
  3904. ValCtx.DiagStream() << "Flags declared=" << declaredFlagsRaw
  3905. << ", actual=" << calcFlagsRaw << "\n";
  3906. }
  3907. static void ValidateSignatureElement(DxilSignatureElement &SE,
  3908. ValidationContext &ValCtx) {
  3909. DXIL::SemanticKind semanticKind = SE.GetSemantic()->GetKind();
  3910. CompType::Kind compKind = SE.GetCompType().GetKind();
  3911. DXIL::InterpolationMode Mode = SE.GetInterpolationMode()->GetKind();
  3912. StringRef Name = SE.GetName();
  3913. if (Name.size() < 1 || Name.size() > 64) {
  3914. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemanticLen);
  3915. }
  3916. if (semanticKind > DXIL::SemanticKind::Arbitrary && semanticKind < DXIL::SemanticKind::Invalid) {
  3917. if (semanticKind != Semantic::GetByName(SE.GetName())->GetKind()) {
  3918. ValCtx.EmitFormatError(ValidationRule::MetaSemaKindMatchesName,
  3919. {SE.GetName(), SE.GetSemantic()->GetName()});
  3920. }
  3921. }
  3922. unsigned compWidth = 0;
  3923. bool compFloat = false;
  3924. bool compInt = false;
  3925. bool compBool = false;
  3926. switch (compKind) {
  3927. case CompType::Kind::U64: compWidth = 64; compInt = true; break;
  3928. case CompType::Kind::I64: compWidth = 64; compInt = true; break;
  3929. case CompType::Kind::U32: compWidth = 32; compInt = true; break;
  3930. case CompType::Kind::I32: compWidth = 32; compInt = true; break;
  3931. case CompType::Kind::U16: compWidth = 16; compInt = true; break;
  3932. case CompType::Kind::I16: compWidth = 16; compInt = true; break;
  3933. case CompType::Kind::I1: compWidth = 1; compBool = true; break;
  3934. case CompType::Kind::F64: compWidth = 64; compFloat = true; break;
  3935. case CompType::Kind::F32: compWidth = 32; compFloat = true; break;
  3936. case CompType::Kind::F16: compWidth = 16; compFloat = true; break;
  3937. case CompType::Kind::SNormF64: compWidth = 64; compFloat = true; break;
  3938. case CompType::Kind::SNormF32: compWidth = 32; compFloat = true; break;
  3939. case CompType::Kind::SNormF16: compWidth = 16; compFloat = true; break;
  3940. case CompType::Kind::UNormF64: compWidth = 64; compFloat = true; break;
  3941. case CompType::Kind::UNormF32: compWidth = 32; compFloat = true; break;
  3942. case CompType::Kind::UNormF16: compWidth = 16; compFloat = true; break;
  3943. case CompType::Kind::Invalid:
  3944. default:
  3945. ValCtx.EmitFormatError(ValidationRule::MetaSignatureCompType, { SE.GetName() });
  3946. break;
  3947. }
  3948. if (compInt || compBool) {
  3949. switch (Mode) {
  3950. case DXIL::InterpolationMode::Linear:
  3951. case DXIL::InterpolationMode::LinearCentroid:
  3952. case DXIL::InterpolationMode::LinearNoperspective:
  3953. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  3954. case DXIL::InterpolationMode::LinearSample:
  3955. case DXIL::InterpolationMode::LinearNoperspectiveSample: {
  3956. ValCtx.EmitFormatError(ValidationRule::MetaIntegerInterpMode, {SE.GetName()});
  3957. } break;
  3958. default:
  3959. break;
  3960. }
  3961. }
  3962. // Elements that should not appear in the Dxil signature:
  3963. bool bAllowedInSig = true;
  3964. bool bShouldBeAllocated = true;
  3965. switch (SE.GetInterpretation()) {
  3966. case DXIL::SemanticInterpretationKind::NA:
  3967. case DXIL::SemanticInterpretationKind::NotInSig:
  3968. case DXIL::SemanticInterpretationKind::Invalid:
  3969. bAllowedInSig = false;
  3970. __fallthrough;
  3971. case DXIL::SemanticInterpretationKind::NotPacked:
  3972. case DXIL::SemanticInterpretationKind::Shadow:
  3973. bShouldBeAllocated = false;
  3974. break;
  3975. default:
  3976. break;
  3977. }
  3978. const char *inputOutput = nullptr;
  3979. if (SE.IsInput())
  3980. inputOutput = "Input";
  3981. else if (SE.IsOutput())
  3982. inputOutput = "Output";
  3983. else
  3984. inputOutput = "PatchConstant";
  3985. if (!bAllowedInSig) {
  3986. ValCtx.EmitFormatError(
  3987. ValidationRule::SmSemantic,
  3988. {SE.GetName(), ValCtx.DxilMod.GetShaderModel()->GetKindName(), inputOutput});
  3989. } else if (bShouldBeAllocated && !SE.IsAllocated()) {
  3990. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldBeAllocated,
  3991. {inputOutput, SE.GetName()});
  3992. } else if (!bShouldBeAllocated && SE.IsAllocated()) {
  3993. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldNotBeAllocated,
  3994. {inputOutput, SE.GetName()});
  3995. }
  3996. bool bIsClipCull = false;
  3997. bool bIsTessfactor = false;
  3998. bool bIsBarycentric = false;
  3999. switch (semanticKind) {
  4000. case DXIL::SemanticKind::Depth:
  4001. case DXIL::SemanticKind::DepthGreaterEqual:
  4002. case DXIL::SemanticKind::DepthLessEqual:
  4003. if (!compFloat || compWidth > 32 || SE.GetCols() != 1) {
  4004. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4005. {SE.GetSemantic()->GetName(), "float"});
  4006. }
  4007. break;
  4008. case DXIL::SemanticKind::Coverage:
  4009. DXASSERT(!SE.IsInput() || !bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  4010. __fallthrough;
  4011. case DXIL::SemanticKind::InnerCoverage:
  4012. case DXIL::SemanticKind::OutputControlPointID:
  4013. if (compKind != CompType::Kind::U32 || SE.GetCols() != 1) {
  4014. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4015. {SE.GetSemantic()->GetName(), "uint"});
  4016. }
  4017. break;
  4018. case DXIL::SemanticKind::Position:
  4019. if (!compFloat || compWidth > 32 || SE.GetCols() != 4) {
  4020. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4021. {SE.GetSemantic()->GetName(), "float4"});
  4022. }
  4023. break;
  4024. case DXIL::SemanticKind::Target:
  4025. if (compWidth > 32) {
  4026. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4027. {SE.GetSemantic()->GetName(), "float/int/uint"});
  4028. }
  4029. break;
  4030. case DXIL::SemanticKind::ClipDistance:
  4031. case DXIL::SemanticKind::CullDistance:
  4032. bIsClipCull = true;
  4033. if (!compFloat || compWidth > 32) {
  4034. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4035. {SE.GetSemantic()->GetName(), "float"});
  4036. }
  4037. // NOTE: clip cull distance size is checked at ValidateSignature.
  4038. break;
  4039. case DXIL::SemanticKind::IsFrontFace: {
  4040. if (!(compInt && compWidth == 32) || SE.GetCols() != 1) {
  4041. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4042. {SE.GetSemantic()->GetName(), "uint"});
  4043. }
  4044. } break;
  4045. case DXIL::SemanticKind::RenderTargetArrayIndex:
  4046. case DXIL::SemanticKind::ViewPortArrayIndex:
  4047. case DXIL::SemanticKind::VertexID:
  4048. case DXIL::SemanticKind::PrimitiveID:
  4049. case DXIL::SemanticKind::InstanceID:
  4050. case DXIL::SemanticKind::GSInstanceID:
  4051. case DXIL::SemanticKind::SampleIndex:
  4052. case DXIL::SemanticKind::StencilRef:
  4053. case DXIL::SemanticKind::ShadingRate:
  4054. if ((compKind != CompType::Kind::U32 && compKind != CompType::Kind::U16) || SE.GetCols() != 1) {
  4055. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4056. {SE.GetSemantic()->GetName(), "uint"});
  4057. }
  4058. break;
  4059. case DXIL::SemanticKind::CullPrimitive: {
  4060. if (!(compBool && compWidth == 1) || SE.GetCols() != 1) {
  4061. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4062. {SE.GetSemantic()->GetName(), "bool"});
  4063. }
  4064. } break;
  4065. case DXIL::SemanticKind::TessFactor:
  4066. case DXIL::SemanticKind::InsideTessFactor:
  4067. // NOTE: the size check is at CheckPatchConstantSemantic.
  4068. bIsTessfactor = true;
  4069. if (!compFloat || compWidth > 32) {
  4070. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  4071. {SE.GetSemantic()->GetName(), "float"});
  4072. }
  4073. break;
  4074. case DXIL::SemanticKind::Arbitrary:
  4075. break;
  4076. case DXIL::SemanticKind::DomainLocation:
  4077. case DXIL::SemanticKind::Invalid:
  4078. DXASSERT(!bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  4079. break;
  4080. case DXIL::SemanticKind::Barycentrics:
  4081. bIsBarycentric = true;
  4082. if (!compFloat || compWidth > 32) {
  4083. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType, {SE.GetSemantic()->GetName(), "float"});
  4084. }
  4085. if (Mode != InterpolationMode::Kind::Linear &&
  4086. Mode != InterpolationMode::Kind::LinearCentroid &&
  4087. Mode != InterpolationMode::Kind::LinearNoperspective &&
  4088. Mode != InterpolationMode::Kind::LinearNoperspectiveCentroid &&
  4089. Mode != InterpolationMode::Kind::LinearNoperspectiveSample &&
  4090. Mode != InterpolationMode::Kind::LinearSample) {
  4091. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsInterpolation);
  4092. }
  4093. if (SE.GetCols() != 3) {
  4094. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsFloat3);
  4095. }
  4096. break;
  4097. default:
  4098. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemaKindValid);
  4099. break;
  4100. }
  4101. if (ValCtx.DxilMod.GetShaderModel()->IsGS() && SE.IsOutput()) {
  4102. if (SE.GetOutputStream() >= DXIL::kNumOutputStreams) {
  4103. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  4104. {std::to_string(SE.GetOutputStream()),
  4105. std::to_string(DXIL::kNumOutputStreams - 1)});
  4106. }
  4107. } else {
  4108. if (SE.GetOutputStream() > 0) {
  4109. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  4110. {std::to_string(SE.GetOutputStream()),
  4111. "0"});
  4112. }
  4113. }
  4114. if (ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  4115. if (SE.GetOutputStream() != 0) {
  4116. if (ValCtx.DxilMod.GetStreamPrimitiveTopology() !=
  4117. DXIL::PrimitiveTopology::PointList) {
  4118. ValCtx.EmitSignatureError(&SE,
  4119. ValidationRule::SmMultiStreamMustBePoint);
  4120. }
  4121. }
  4122. }
  4123. if (semanticKind == DXIL::SemanticKind::Target) {
  4124. // Verify packed row == semantic index
  4125. unsigned row = SE.GetStartRow();
  4126. for (unsigned i : SE.GetSemanticIndexVec()) {
  4127. if (row != i) {
  4128. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetIndexMatchesRow);
  4129. }
  4130. ++row;
  4131. }
  4132. // Verify packed col is 0
  4133. if (SE.GetStartCol() != 0) {
  4134. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetCol0);
  4135. }
  4136. // Verify max row used < 8
  4137. if (SE.GetStartRow() + SE.GetRows() > 8) {
  4138. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {"SV_Target", "7"});
  4139. }
  4140. } else if (bAllowedInSig && semanticKind != DXIL::SemanticKind::Arbitrary) {
  4141. if (bIsBarycentric) {
  4142. if (SE.GetSemanticStartIndex() > 1) {
  4143. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, { SE.GetSemantic()->GetName(), "1" });
  4144. }
  4145. }
  4146. else if (!bIsClipCull && SE.GetSemanticStartIndex() > 0) {
  4147. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {SE.GetSemantic()->GetName(), "0"});
  4148. }
  4149. // Maximum rows is 1 for system values other than Target
  4150. // with the exception of tessfactors, which are validated in CheckPatchConstantSemantic
  4151. // and ClipDistance/CullDistance, which have other custom constraints.
  4152. if (!bIsTessfactor && !bIsClipCull && SE.GetRows() > 1) {
  4153. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSystemValueRows);
  4154. }
  4155. }
  4156. if (SE.GetCols() + (SE.IsAllocated() ? SE.GetStartCol() : 0) > 4) {
  4157. unsigned size = (SE.GetRows() - 1) * 4 + SE.GetCols();
  4158. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  4159. {SE.GetName(),
  4160. std::to_string(SE.GetStartRow()),
  4161. std::to_string(SE.GetStartCol()),
  4162. std::to_string(size)});
  4163. }
  4164. if (!SE.GetInterpolationMode()->IsValid()) {
  4165. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaInterpModeValid);
  4166. }
  4167. }
  4168. static void ValidateSignatureOverlap(
  4169. DxilSignatureElement &E, unsigned maxScalars,
  4170. DxilSignatureAllocator &allocator,
  4171. ValidationContext &ValCtx) {
  4172. // Skip entries that are not or should not be allocated. Validation occurs in ValidateSignatureElement.
  4173. if (!E.IsAllocated())
  4174. return;
  4175. switch (E.GetInterpretation()) {
  4176. case DXIL::SemanticInterpretationKind::NA:
  4177. case DXIL::SemanticInterpretationKind::NotInSig:
  4178. case DXIL::SemanticInterpretationKind::Invalid:
  4179. case DXIL::SemanticInterpretationKind::NotPacked:
  4180. case DXIL::SemanticInterpretationKind::Shadow:
  4181. return;
  4182. default:
  4183. break;
  4184. }
  4185. DxilPackElement PE(&E, allocator.UseMinPrecision());
  4186. DxilSignatureAllocator::ConflictType conflict = allocator.DetectRowConflict(&PE, E.GetStartRow());
  4187. if (conflict == DxilSignatureAllocator::kNoConflict || conflict == DxilSignatureAllocator::kInsufficientFreeComponents)
  4188. conflict = allocator.DetectColConflict(&PE, E.GetStartRow(), E.GetStartCol());
  4189. switch (conflict) {
  4190. case DxilSignatureAllocator::kNoConflict:
  4191. allocator.PlaceElement(&PE, E.GetStartRow(), E.GetStartCol());
  4192. break;
  4193. case DxilSignatureAllocator::kConflictsWithIndexed:
  4194. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  4195. {E.GetName(),
  4196. std::to_string(E.GetStartRow()),
  4197. std::to_string(E.GetStartCol()),
  4198. std::to_string(E.GetRows()),
  4199. std::to_string(E.GetCols())});
  4200. break;
  4201. case DxilSignatureAllocator::kConflictsWithIndexedTessFactor:
  4202. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  4203. {E.GetName(),
  4204. std::to_string(E.GetStartRow()),
  4205. std::to_string(E.GetStartCol()),
  4206. std::to_string(E.GetRows()),
  4207. std::to_string(E.GetCols())});
  4208. break;
  4209. case DxilSignatureAllocator::kConflictsWithInterpolationMode:
  4210. ValCtx.EmitFormatError(ValidationRule::MetaInterpModeInOneRow,
  4211. {E.GetName(),
  4212. std::to_string(E.GetStartRow()),
  4213. std::to_string(E.GetStartCol()),
  4214. std::to_string(E.GetRows()),
  4215. std::to_string(E.GetCols())});
  4216. break;
  4217. case DxilSignatureAllocator::kInsufficientFreeComponents:
  4218. DXASSERT(false, "otherwise, conflict not translated");
  4219. break;
  4220. case DxilSignatureAllocator::kOverlapElement:
  4221. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOverlap,
  4222. {E.GetName(),
  4223. std::to_string(E.GetStartRow()),
  4224. std::to_string(E.GetStartCol()),
  4225. std::to_string(E.GetRows()),
  4226. std::to_string(E.GetCols())});
  4227. break;
  4228. case DxilSignatureAllocator::kIllegalComponentOrder:
  4229. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIllegalComponentOrder,
  4230. {E.GetName(),
  4231. std::to_string(E.GetStartRow()),
  4232. std::to_string(E.GetStartCol()),
  4233. std::to_string(E.GetRows()),
  4234. std::to_string(E.GetCols())});
  4235. break;
  4236. case DxilSignatureAllocator::kConflictFit:
  4237. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  4238. {E.GetName(),
  4239. std::to_string(E.GetStartRow()),
  4240. std::to_string(E.GetStartCol()),
  4241. std::to_string(E.GetRows()),
  4242. std::to_string(E.GetCols())});
  4243. break;
  4244. case DxilSignatureAllocator::kConflictDataWidth:
  4245. ValCtx.EmitFormatError(ValidationRule::MetaSignatureDataWidth,
  4246. {E.GetName(),
  4247. std::to_string(E.GetStartRow()),
  4248. std::to_string(E.GetStartCol()),
  4249. std::to_string(E.GetRows()),
  4250. std::to_string(E.GetCols())});
  4251. break;
  4252. default:
  4253. DXASSERT(false, "otherwise, unrecognized conflict type from DxilSignatureAllocator");
  4254. }
  4255. }
  4256. static void ValidateSignature(ValidationContext &ValCtx, const DxilSignature &S,
  4257. EntryStatus &Status,
  4258. unsigned maxScalars) {
  4259. DxilSignatureAllocator allocator[DXIL::kNumOutputStreams] = {
  4260. {32, ValCtx.DxilMod.GetUseMinPrecision()},
  4261. {32, ValCtx.DxilMod.GetUseMinPrecision()},
  4262. {32, ValCtx.DxilMod.GetUseMinPrecision()},
  4263. {32, ValCtx.DxilMod.GetUseMinPrecision()}};
  4264. unordered_set<unsigned> semanticUsageSet[DXIL::kNumOutputStreams];
  4265. StringMap<unordered_set<unsigned>> semanticIndexMap[DXIL::kNumOutputStreams];
  4266. unordered_set<unsigned> clipcullRowSet[DXIL::kNumOutputStreams];
  4267. unsigned clipcullComponents[DXIL::kNumOutputStreams] = {0, 0, 0, 0};
  4268. bool isOutput = S.IsOutput();
  4269. unsigned TargetMask = 0;
  4270. DXIL::SemanticKind DepthKind = DXIL::SemanticKind::Invalid;
  4271. const InterpolationMode *prevBaryInterpMode = nullptr;
  4272. unsigned numBarycentrics = 0;
  4273. for (auto &E : S.GetElements()) {
  4274. DXIL::SemanticKind semanticKind = E->GetSemantic()->GetKind();
  4275. ValidateSignatureElement(*E, ValCtx);
  4276. // Avoid OOB indexing on streamId.
  4277. unsigned streamId = E->GetOutputStream();
  4278. if (streamId >= DXIL::kNumOutputStreams ||
  4279. !isOutput ||
  4280. !ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  4281. streamId = 0;
  4282. }
  4283. // Semantic index overlap check, keyed by name.
  4284. std::string nameUpper(E->GetName());
  4285. std::transform(nameUpper.begin(), nameUpper.end(), nameUpper.begin(), ::toupper);
  4286. unordered_set<unsigned> &semIdxSet = semanticIndexMap[streamId][nameUpper];
  4287. for (unsigned semIdx : E->GetSemanticIndexVec()) {
  4288. if (semIdxSet.count(semIdx) > 0) {
  4289. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  4290. {E->GetName(), std::to_string(semIdx)});
  4291. return;
  4292. } else
  4293. semIdxSet.insert(semIdx);
  4294. }
  4295. // SV_Target has special rules
  4296. if (semanticKind == DXIL::SemanticKind::Target) {
  4297. // Validate target overlap
  4298. if (E->GetStartRow() + E->GetRows() <= 8) {
  4299. unsigned mask = ((1 << E->GetRows()) - 1) << E->GetStartRow();
  4300. if (TargetMask & mask) {
  4301. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  4302. {"SV_Target", std::to_string(E->GetStartRow())});
  4303. }
  4304. TargetMask = TargetMask | mask;
  4305. }
  4306. if (E->GetRows() > 1) {
  4307. ValCtx.EmitError(ValidationRule::SmNoPSOutputIdx);
  4308. }
  4309. continue;
  4310. }
  4311. if (E->GetSemantic()->IsInvalid())
  4312. continue;
  4313. // validate system value semantic rules
  4314. switch (semanticKind) {
  4315. case DXIL::SemanticKind::Arbitrary:
  4316. break;
  4317. case DXIL::SemanticKind::ClipDistance:
  4318. case DXIL::SemanticKind::CullDistance:
  4319. // Validate max 8 components across 2 rows (registers)
  4320. for (unsigned rowIdx = 0; rowIdx < E->GetRows(); rowIdx++)
  4321. clipcullRowSet[streamId].insert(E->GetStartRow() + rowIdx);
  4322. if (clipcullRowSet[streamId].size() > 2) {
  4323. ValCtx.EmitError(ValidationRule::MetaClipCullMaxRows);
  4324. }
  4325. clipcullComponents[streamId] += E->GetCols();
  4326. if (clipcullComponents[streamId] > 8) {
  4327. ValCtx.EmitError(ValidationRule::MetaClipCullMaxComponents);
  4328. }
  4329. break;
  4330. case DXIL::SemanticKind::Depth:
  4331. case DXIL::SemanticKind::DepthGreaterEqual:
  4332. case DXIL::SemanticKind::DepthLessEqual:
  4333. if (DepthKind != DXIL::SemanticKind::Invalid) {
  4334. ValCtx.EmitError(ValidationRule::SmPSMultipleDepthSemantic);
  4335. }
  4336. DepthKind = semanticKind;
  4337. break;
  4338. case DXIL::SemanticKind::Barycentrics: {
  4339. // There can only be up to two SV_Barycentrics
  4340. // with differeent perspective interpolation modes.
  4341. if (numBarycentrics++ > 1) {
  4342. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  4343. break;
  4344. }
  4345. const InterpolationMode *mode = E->GetInterpolationMode();
  4346. if (prevBaryInterpMode) {
  4347. if ((mode->IsAnyNoPerspective() && prevBaryInterpMode->IsAnyNoPerspective())
  4348. || (!mode->IsAnyNoPerspective() && !prevBaryInterpMode->IsAnyNoPerspective())) {
  4349. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  4350. }
  4351. }
  4352. prevBaryInterpMode = mode;
  4353. break;
  4354. }
  4355. default:
  4356. if (semanticUsageSet[streamId].count(static_cast<unsigned>(semanticKind)) > 0) {
  4357. ValCtx.EmitFormatError(ValidationRule::MetaDuplicateSysValue,
  4358. {E->GetSemantic()->GetName()});
  4359. }
  4360. semanticUsageSet[streamId].insert(static_cast<unsigned>(semanticKind));
  4361. break;
  4362. }
  4363. // Packed element overlap check.
  4364. ValidateSignatureOverlap(*E.get(), maxScalars, allocator[streamId], ValCtx);
  4365. if (isOutput && semanticKind == DXIL::SemanticKind::Position) {
  4366. Status.hasOutputPosition[E->GetOutputStream()] = true;
  4367. }
  4368. }
  4369. if (Status.hasViewID && S.IsInput() && ValCtx.DxilMod.GetShaderModel()->GetKind() == DXIL::ShaderKind::Pixel) {
  4370. // Ensure sufficient space for ViewID:
  4371. DxilSignatureAllocator::DummyElement viewID;
  4372. viewID.rows = 1;
  4373. viewID.cols = 1;
  4374. viewID.kind = DXIL::SemanticKind::Arbitrary;
  4375. viewID.interpolation = DXIL::InterpolationMode::Constant;
  4376. viewID.interpretation = DXIL::SemanticInterpretationKind::SGV;
  4377. allocator[0].PackNext(&viewID, 0, 32);
  4378. if (!viewID.IsAllocated()) {
  4379. ValCtx.EmitError(ValidationRule::SmViewIDNeedsSlot);
  4380. }
  4381. }
  4382. }
  4383. static void ValidateNoInterpModeSignature(ValidationContext &ValCtx, const DxilSignature &S) {
  4384. for (auto &E : S.GetElements()) {
  4385. if (!E->GetInterpolationMode()->IsUndefined()) {
  4386. ValCtx.EmitSignatureError(E.get(), ValidationRule::SmNoInterpMode);
  4387. }
  4388. }
  4389. }
  4390. static void ValidateConstantInterpModeSignature(ValidationContext &ValCtx, const DxilSignature &S) {
  4391. for (auto &E : S.GetElements()) {
  4392. if (!E->GetInterpolationMode()->IsConstant()) {
  4393. ValCtx.EmitSignatureError(E.get(), ValidationRule::SmConstantInterpMode);
  4394. }
  4395. }
  4396. }
  4397. static void ValidateEntrySignatures(ValidationContext &ValCtx,
  4398. const DxilEntryProps &entryProps,
  4399. EntryStatus &Status,
  4400. Function &F) {
  4401. const DxilFunctionProps &props = entryProps.props;
  4402. const DxilEntrySignature &S = entryProps.sig;
  4403. if (props.IsRay()) {
  4404. // No signatures allowed
  4405. if (!S.InputSignature.GetElements().empty() ||
  4406. !S.OutputSignature.GetElements().empty() ||
  4407. !S.PatchConstOrPrimSignature.GetElements().empty()) {
  4408. ValCtx.EmitFormatError(ValidationRule::SmRayShaderSignatures, { F.getName() });
  4409. }
  4410. // Validate payload/attribute/params sizes
  4411. unsigned payloadSize = 0;
  4412. unsigned attrSize = 0;
  4413. auto itPayload = F.arg_begin();
  4414. auto itAttr = itPayload;
  4415. if (itAttr != F.arg_end())
  4416. itAttr++;
  4417. DataLayout DL(F.getParent());
  4418. switch (props.shaderKind) {
  4419. case DXIL::ShaderKind::AnyHit:
  4420. case DXIL::ShaderKind::ClosestHit:
  4421. if (itAttr != F.arg_end()) {
  4422. Type *Ty = itAttr->getType();
  4423. if (Ty->isPointerTy())
  4424. Ty = Ty->getPointerElementType();
  4425. attrSize = (unsigned)std::min(DL.getTypeAllocSize(Ty), (uint64_t)UINT_MAX);
  4426. }
  4427. case DXIL::ShaderKind::Miss:
  4428. case DXIL::ShaderKind::Callable:
  4429. if (itPayload != F.arg_end()) {
  4430. Type *Ty = itPayload->getType();
  4431. if (Ty->isPointerTy())
  4432. Ty = Ty->getPointerElementType();
  4433. payloadSize = (unsigned)std::min(DL.getTypeAllocSize(Ty), (uint64_t)UINT_MAX);
  4434. }
  4435. break;
  4436. }
  4437. if (props.ShaderProps.Ray.payloadSizeInBytes < payloadSize) {
  4438. ValCtx.EmitFormatError(ValidationRule::SmRayShaderPayloadSize,
  4439. { F.getName(), props.IsCallable() ? "params" : "payload" });
  4440. }
  4441. if (props.ShaderProps.Ray.attributeSizeInBytes < attrSize) {
  4442. ValCtx.EmitFormatError(ValidationRule::SmRayShaderPayloadSize,
  4443. { F.getName(), "attribute" });
  4444. }
  4445. return;
  4446. }
  4447. bool isPS = props.IsPS();
  4448. bool isVS = props.IsVS();
  4449. bool isGS = props.IsGS();
  4450. bool isCS = props.IsCS();
  4451. bool isMS = props.IsMS();
  4452. if (isPS) {
  4453. // PS output no interp mode.
  4454. ValidateNoInterpModeSignature(ValCtx, S.OutputSignature);
  4455. } else if (isVS) {
  4456. // VS input no interp mode.
  4457. ValidateNoInterpModeSignature(ValCtx, S.InputSignature);
  4458. }
  4459. if (isMS) {
  4460. // primitive output constant interp mode.
  4461. ValidateConstantInterpModeSignature(ValCtx, S.PatchConstOrPrimSignature);
  4462. } else {
  4463. // patch constant no interp mode.
  4464. ValidateNoInterpModeSignature(ValCtx, S.PatchConstOrPrimSignature);
  4465. }
  4466. unsigned maxInputScalars = DXIL::kMaxInputTotalScalars;
  4467. unsigned maxOutputScalars = 0;
  4468. unsigned maxPatchConstantScalars = 0;
  4469. switch (props.shaderKind) {
  4470. case DXIL::ShaderKind::Compute:
  4471. break;
  4472. case DXIL::ShaderKind::Vertex:
  4473. case DXIL::ShaderKind::Geometry:
  4474. case DXIL::ShaderKind::Pixel:
  4475. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  4476. break;
  4477. case DXIL::ShaderKind::Hull:
  4478. case DXIL::ShaderKind::Domain:
  4479. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  4480. maxPatchConstantScalars = DXIL::kMaxHSOutputPatchConstantTotalScalars;
  4481. break;
  4482. case DXIL::ShaderKind::Mesh:
  4483. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  4484. maxPatchConstantScalars = DXIL::kMaxOutputTotalScalars;
  4485. break;
  4486. case DXIL::ShaderKind::Amplification:
  4487. default:
  4488. break;
  4489. }
  4490. ValidateSignature(ValCtx, S.InputSignature, Status, maxInputScalars);
  4491. ValidateSignature(ValCtx, S.OutputSignature, Status, maxOutputScalars);
  4492. ValidateSignature(ValCtx, S.PatchConstOrPrimSignature, Status,
  4493. maxPatchConstantScalars);
  4494. if (isPS) {
  4495. // Gather execution information.
  4496. hlsl::PSExecutionInfo PSExec;
  4497. for (auto &E :S.InputSignature.GetElements()) {
  4498. if (E->GetKind() == DXIL::SemanticKind::SampleIndex) {
  4499. PSExec.SuperSampling = true;
  4500. continue;
  4501. }
  4502. const InterpolationMode *IM = E->GetInterpolationMode();
  4503. if (IM->IsLinearSample() || IM->IsLinearNoperspectiveSample()) {
  4504. PSExec.SuperSampling = true;
  4505. }
  4506. if (E->GetKind() == DXIL::SemanticKind::Position) {
  4507. PSExec.PositionInterpolationMode = IM;
  4508. }
  4509. }
  4510. for (auto &E : S.OutputSignature.GetElements()) {
  4511. if (E->IsAnyDepth()) {
  4512. PSExec.OutputDepthKind = E->GetKind();
  4513. break;
  4514. }
  4515. }
  4516. if (!PSExec.SuperSampling &&
  4517. PSExec.OutputDepthKind != DXIL::SemanticKind::Invalid &&
  4518. PSExec.OutputDepthKind != DXIL::SemanticKind::Depth) {
  4519. if (PSExec.PositionInterpolationMode != nullptr) {
  4520. if (!PSExec.PositionInterpolationMode->IsUndefined() &&
  4521. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveCentroid() &&
  4522. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveSample()) {
  4523. ValCtx.EmitError(ValidationRule::SmPSConsistentInterp);
  4524. }
  4525. }
  4526. }
  4527. // Validate PS output semantic.
  4528. const DxilSignature &outputSig = S.OutputSignature;
  4529. for (auto &SE : outputSig.GetElements()) {
  4530. Semantic::Kind semanticKind = SE->GetSemantic()->GetKind();
  4531. switch (semanticKind) {
  4532. case Semantic::Kind::Target:
  4533. case Semantic::Kind::Coverage:
  4534. case Semantic::Kind::Depth:
  4535. case Semantic::Kind::DepthGreaterEqual:
  4536. case Semantic::Kind::DepthLessEqual:
  4537. case Semantic::Kind::StencilRef:
  4538. break;
  4539. default: {
  4540. ValCtx.EmitFormatError(ValidationRule::SmPSOutputSemantic, {SE->GetName()});
  4541. } break;
  4542. }
  4543. }
  4544. }
  4545. if (isGS) {
  4546. unsigned maxVertexCount = props.ShaderProps.GS.maxVertexCount;
  4547. unsigned outputScalarCount = 0;
  4548. const DxilSignature &outSig = S.OutputSignature;
  4549. for (auto &SE : outSig.GetElements()) {
  4550. outputScalarCount += SE->GetRows() * SE->GetCols();
  4551. }
  4552. unsigned totalOutputScalars = maxVertexCount * outputScalarCount;
  4553. if (totalOutputScalars > DXIL::kMaxGSOutputTotalScalars) {
  4554. ValCtx.EmitFormatError(
  4555. ValidationRule::SmGSTotalOutputVertexDataRange,
  4556. {std::to_string(maxVertexCount),
  4557. std::to_string(outputScalarCount),
  4558. std::to_string(totalOutputScalars),
  4559. std::to_string(DXIL::kMaxGSOutputTotalScalars)});
  4560. }
  4561. }
  4562. if (isCS) {
  4563. if (!S.InputSignature.GetElements().empty() ||
  4564. !S.OutputSignature.GetElements().empty() ||
  4565. !S.PatchConstOrPrimSignature.GetElements().empty()) {
  4566. ValCtx.EmitError(ValidationRule::SmCSNoSignatures);
  4567. }
  4568. }
  4569. if (isMS) {
  4570. unsigned VertexSignatureRows = S.OutputSignature.GetRowCount();
  4571. if (VertexSignatureRows > DXIL::kMaxMSVSigRows) {
  4572. ValCtx.EmitFormatError(
  4573. ValidationRule::SmMeshVSigRowCount,
  4574. { F.getName(), std::to_string(DXIL::kMaxMSVSigRows) });
  4575. }
  4576. unsigned PrimitiveSignatureRows = S.PatchConstOrPrimSignature.GetRowCount();
  4577. if (PrimitiveSignatureRows > DXIL::kMaxMSPSigRows) {
  4578. ValCtx.EmitFormatError(
  4579. ValidationRule::SmMeshPSigRowCount,
  4580. { F.getName(), std::to_string(DXIL::kMaxMSPSigRows) });
  4581. }
  4582. if (VertexSignatureRows + PrimitiveSignatureRows > DXIL::kMaxMSTotalSigRows) {
  4583. ValCtx.EmitFormatError(
  4584. ValidationRule::SmMeshTotalSigRowCount,
  4585. { F.getName(), std::to_string(DXIL::kMaxMSTotalSigRows) });
  4586. }
  4587. const unsigned kScalarSizeForMSAttributes = 4;
  4588. #define ALIGN32(n) (((n) + 31) & ~31)
  4589. unsigned maxAlign32VertexCount = ALIGN32(props.ShaderProps.MS.maxVertexCount);
  4590. unsigned maxAlign32PrimitiveCount = ALIGN32(props.ShaderProps.MS.maxPrimitiveCount);
  4591. unsigned totalOutputScalars = 0;
  4592. for (auto &SE : S.OutputSignature.GetElements()) {
  4593. totalOutputScalars += SE->GetRows() * SE->GetCols() * maxAlign32VertexCount;
  4594. }
  4595. for (auto &SE : S.PatchConstOrPrimSignature.GetElements()) {
  4596. totalOutputScalars += SE->GetRows() * SE->GetCols() * maxAlign32PrimitiveCount;
  4597. }
  4598. if (totalOutputScalars*kScalarSizeForMSAttributes > DXIL::kMaxMSOutputTotalBytes) {
  4599. ValCtx.EmitFormatError(
  4600. ValidationRule::SmMeshShaderOutputSize,
  4601. { F.getName(), std::to_string(DXIL::kMaxMSOutputTotalBytes) });
  4602. }
  4603. unsigned totalInputOutputBytes = totalOutputScalars*kScalarSizeForMSAttributes + props.ShaderProps.MS.payloadSizeInBytes;
  4604. if (totalInputOutputBytes > DXIL::kMaxMSInputOutputTotalBytes) {
  4605. ValCtx.EmitFormatError(
  4606. ValidationRule::SmMeshShaderInOutSize,
  4607. { F.getName(), std::to_string(DXIL::kMaxMSInputOutputTotalBytes) });
  4608. }
  4609. }
  4610. }
  4611. static void ValidateEntrySignatures(ValidationContext &ValCtx) {
  4612. DxilModule &DM = ValCtx.DxilMod;
  4613. if (ValCtx.isLibProfile) {
  4614. for (Function &F : DM.GetModule()->functions()) {
  4615. if (DM.HasDxilEntryProps(&F)) {
  4616. DxilEntryProps &entryProps = DM.GetDxilEntryProps(&F);
  4617. EntryStatus &Status = ValCtx.GetEntryStatus(&F);
  4618. ValidateEntrySignatures(ValCtx, entryProps, Status, F);
  4619. }
  4620. }
  4621. } else {
  4622. Function *Entry = DM.GetEntryFunction();
  4623. if (!DM.HasDxilEntryProps(Entry)) {
  4624. // must have props.
  4625. ValCtx.EmitError(ValidationRule::MetaNoEntryPropsForEntry);
  4626. return;
  4627. }
  4628. EntryStatus &Status = ValCtx.GetEntryStatus(Entry);
  4629. DxilEntryProps &entryProps = DM.GetDxilEntryProps(Entry);
  4630. ValidateEntrySignatures(ValCtx, entryProps, Status, *Entry);
  4631. }
  4632. }
  4633. static void CheckPatchConstantSemantic(ValidationContext &ValCtx,
  4634. const DxilEntryProps &EntryProps,
  4635. EntryStatus &Status) {
  4636. const DxilFunctionProps &props = EntryProps.props;
  4637. bool isHS = props.IsHS();
  4638. DXIL::TessellatorDomain domain =
  4639. isHS ? props.ShaderProps.HS.domain : props.ShaderProps.DS.domain;
  4640. const DxilSignature &patchConstantSig = EntryProps.sig.PatchConstOrPrimSignature;
  4641. const unsigned kQuadEdgeSize = 4;
  4642. const unsigned kQuadInsideSize = 2;
  4643. const unsigned kQuadDomainLocSize = 2;
  4644. const unsigned kTriEdgeSize = 3;
  4645. const unsigned kTriInsideSize = 1;
  4646. const unsigned kTriDomainLocSize = 3;
  4647. const unsigned kIsolineEdgeSize = 2;
  4648. const unsigned kIsolineInsideSize = 0;
  4649. const unsigned kIsolineDomainLocSize = 3;
  4650. const char *domainName = "";
  4651. DXIL::SemanticKind kEdgeSemantic = DXIL::SemanticKind::TessFactor;
  4652. unsigned edgeSize = 0;
  4653. DXIL::SemanticKind kInsideSemantic = DXIL::SemanticKind::InsideTessFactor;
  4654. unsigned insideSize = 0;
  4655. Status.domainLocSize = 0;
  4656. switch (domain) {
  4657. case DXIL::TessellatorDomain::IsoLine:
  4658. domainName = "IsoLine";
  4659. edgeSize = kIsolineEdgeSize;
  4660. insideSize = kIsolineInsideSize;
  4661. Status.domainLocSize = kIsolineDomainLocSize;
  4662. break;
  4663. case DXIL::TessellatorDomain::Tri:
  4664. domainName = "Tri";
  4665. edgeSize = kTriEdgeSize;
  4666. insideSize = kTriInsideSize;
  4667. Status.domainLocSize = kTriDomainLocSize;
  4668. break;
  4669. case DXIL::TessellatorDomain::Quad:
  4670. domainName = "Quad";
  4671. edgeSize = kQuadEdgeSize;
  4672. insideSize = kQuadInsideSize;
  4673. Status.domainLocSize = kQuadDomainLocSize;
  4674. break;
  4675. default:
  4676. // Don't bother with other tests if domain is invalid
  4677. return;
  4678. }
  4679. bool bFoundEdgeSemantic = false;
  4680. bool bFoundInsideSemantic = false;
  4681. for (auto &SE : patchConstantSig.GetElements()) {
  4682. Semantic::Kind kind = SE->GetSemantic()->GetKind();
  4683. if (kind == kEdgeSemantic) {
  4684. bFoundEdgeSemantic = true;
  4685. if (SE->GetRows() != edgeSize || SE->GetCols() > 1) {
  4686. ValCtx.EmitFormatError(ValidationRule::SmTessFactorSizeMatchDomain,
  4687. {std::to_string(SE->GetRows()),
  4688. std::to_string(SE->GetCols()), domainName,
  4689. std::to_string(edgeSize)});
  4690. }
  4691. } else if (kind == kInsideSemantic) {
  4692. bFoundInsideSemantic = true;
  4693. if (SE->GetRows() != insideSize || SE->GetCols() > 1) {
  4694. ValCtx.EmitFormatError(
  4695. ValidationRule::SmInsideTessFactorSizeMatchDomain,
  4696. {std::to_string(SE->GetRows()), std::to_string(SE->GetCols()),
  4697. domainName, std::to_string(insideSize)});
  4698. }
  4699. }
  4700. }
  4701. if (isHS) {
  4702. if (!bFoundEdgeSemantic) {
  4703. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  4704. }
  4705. if (!bFoundInsideSemantic && domain != DXIL::TessellatorDomain::IsoLine) {
  4706. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  4707. }
  4708. }
  4709. }
  4710. static void ValidatePassThruHS(ValidationContext &ValCtx,
  4711. const DxilEntryProps &entryProps, Function *F) {
  4712. // Check pass thru HS.
  4713. if (F->isDeclaration()) {
  4714. const auto &props = entryProps.props;
  4715. if (props.IsHS()) {
  4716. const auto &HS = props.ShaderProps.HS;
  4717. if (HS.inputControlPoints < HS.outputControlPoints) {
  4718. ValCtx.EmitError(ValidationRule::SmHullPassThruControlPointCountMatch);
  4719. }
  4720. // Check declared control point outputs storage amounts are ok to pass
  4721. // through (less output storage than input for control points).
  4722. const DxilSignature &outSig = entryProps.sig.OutputSignature;
  4723. unsigned totalOutputCPScalars = 0;
  4724. for (auto &SE : outSig.GetElements()) {
  4725. totalOutputCPScalars += SE->GetRows() * SE->GetCols();
  4726. }
  4727. if (totalOutputCPScalars * HS.outputControlPoints >
  4728. DXIL::kMaxHSOutputControlPointsTotalScalars) {
  4729. ValCtx.EmitError(ValidationRule::SmOutputControlPointsTotalScalars);
  4730. }
  4731. } else {
  4732. ValCtx.EmitError(ValidationRule::MetaEntryFunction);
  4733. }
  4734. }
  4735. }
  4736. static void ValidateEntryProps(ValidationContext &ValCtx,
  4737. const DxilEntryProps &entryProps,
  4738. EntryStatus &Status) {
  4739. const DxilFunctionProps &props = entryProps.props;
  4740. DXIL::ShaderKind ShaderType = props.shaderKind;
  4741. if (ShaderType == DXIL::ShaderKind::Compute) {
  4742. const auto &CS = props.ShaderProps.CS;
  4743. unsigned x = CS.numThreads[0];
  4744. unsigned y = CS.numThreads[1];
  4745. unsigned z = CS.numThreads[2];
  4746. unsigned threadsInGroup = x * y * z;
  4747. if ((x < DXIL::kMinCSThreadGroupX) || (x > DXIL::kMaxCSThreadGroupX)) {
  4748. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4749. {"X", std::to_string(x),
  4750. std::to_string(DXIL::kMinCSThreadGroupX),
  4751. std::to_string(DXIL::kMaxCSThreadGroupX)});
  4752. }
  4753. if ((y < DXIL::kMinCSThreadGroupY) || (y > DXIL::kMaxCSThreadGroupY)) {
  4754. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4755. {"Y", std::to_string(y),
  4756. std::to_string(DXIL::kMinCSThreadGroupY),
  4757. std::to_string(DXIL::kMaxCSThreadGroupY)});
  4758. }
  4759. if ((z < DXIL::kMinCSThreadGroupZ) || (z > DXIL::kMaxCSThreadGroupZ)) {
  4760. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4761. {"Z", std::to_string(z),
  4762. std::to_string(DXIL::kMinCSThreadGroupZ),
  4763. std::to_string(DXIL::kMaxCSThreadGroupZ)});
  4764. }
  4765. if (threadsInGroup > DXIL::kMaxCSThreadsPerGroup) {
  4766. ValCtx.EmitFormatError(ValidationRule::SmMaxTheadGroup,
  4767. {std::to_string(threadsInGroup),
  4768. std::to_string(DXIL::kMaxCSThreadsPerGroup)});
  4769. }
  4770. // type of threadID, thread group ID take care by DXIL operation overload
  4771. // check.
  4772. } else if (ShaderType == DXIL::ShaderKind::Mesh) {
  4773. const auto &MS = props.ShaderProps.MS;
  4774. unsigned x = MS.numThreads[0];
  4775. unsigned y = MS.numThreads[1];
  4776. unsigned z = MS.numThreads[2];
  4777. unsigned threadsInGroup = x * y * z;
  4778. if ((x < DXIL::kMinMSASThreadGroupX) || (x > DXIL::kMaxMSASThreadGroupX)) {
  4779. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4780. {"X", std::to_string(x),
  4781. std::to_string(DXIL::kMinMSASThreadGroupX),
  4782. std::to_string(DXIL::kMaxMSASThreadGroupX)});
  4783. }
  4784. if ((y < DXIL::kMinMSASThreadGroupY) || (y > DXIL::kMaxMSASThreadGroupY)) {
  4785. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4786. {"Y", std::to_string(y),
  4787. std::to_string(DXIL::kMinMSASThreadGroupY),
  4788. std::to_string(DXIL::kMaxMSASThreadGroupY)});
  4789. }
  4790. if ((z < DXIL::kMinMSASThreadGroupZ) || (z > DXIL::kMaxMSASThreadGroupZ)) {
  4791. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4792. {"Z", std::to_string(z),
  4793. std::to_string(DXIL::kMinMSASThreadGroupZ),
  4794. std::to_string(DXIL::kMaxMSASThreadGroupZ)});
  4795. }
  4796. if (threadsInGroup > DXIL::kMaxMSASThreadsPerGroup) {
  4797. ValCtx.EmitFormatError(ValidationRule::SmMaxTheadGroup,
  4798. {std::to_string(threadsInGroup),
  4799. std::to_string(DXIL::kMaxMSASThreadsPerGroup)});
  4800. }
  4801. // type of threadID, thread group ID take care by DXIL operation overload
  4802. // check.
  4803. unsigned maxVertexCount = MS.maxVertexCount;
  4804. if (maxVertexCount > DXIL::kMaxMSOutputVertexCount) {
  4805. ValCtx.EmitFormatError(
  4806. ValidationRule::SmMeshShaderMaxVertexCount,
  4807. { std::to_string(DXIL::kMaxMSOutputVertexCount),
  4808. std::to_string(maxVertexCount) });
  4809. }
  4810. unsigned maxPrimitiveCount = MS.maxPrimitiveCount;
  4811. if (maxPrimitiveCount > DXIL::kMaxMSOutputPrimitiveCount) {
  4812. ValCtx.EmitFormatError(
  4813. ValidationRule::SmMeshShaderMaxPrimitiveCount,
  4814. { std::to_string(DXIL::kMaxMSOutputPrimitiveCount),
  4815. std::to_string(maxPrimitiveCount) });
  4816. }
  4817. } else if (ShaderType == DXIL::ShaderKind::Amplification) {
  4818. const auto &AS = props.ShaderProps.AS;
  4819. unsigned x = AS.numThreads[0];
  4820. unsigned y = AS.numThreads[1];
  4821. unsigned z = AS.numThreads[2];
  4822. unsigned threadsInGroup = x * y * z;
  4823. if ((x < DXIL::kMinMSASThreadGroupX) || (x > DXIL::kMaxMSASThreadGroupX)) {
  4824. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4825. {"X", std::to_string(x),
  4826. std::to_string(DXIL::kMinMSASThreadGroupX),
  4827. std::to_string(DXIL::kMaxMSASThreadGroupX)});
  4828. }
  4829. if ((y < DXIL::kMinMSASThreadGroupY) || (y > DXIL::kMaxMSASThreadGroupY)) {
  4830. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4831. {"Y", std::to_string(y),
  4832. std::to_string(DXIL::kMinMSASThreadGroupY),
  4833. std::to_string(DXIL::kMaxMSASThreadGroupY)});
  4834. }
  4835. if ((z < DXIL::kMinMSASThreadGroupZ) || (z > DXIL::kMaxMSASThreadGroupZ)) {
  4836. ValCtx.EmitFormatError(ValidationRule::SmThreadGroupChannelRange,
  4837. {"Z", std::to_string(z),
  4838. std::to_string(DXIL::kMinMSASThreadGroupZ),
  4839. std::to_string(DXIL::kMaxMSASThreadGroupZ)});
  4840. }
  4841. if (threadsInGroup > DXIL::kMaxMSASThreadsPerGroup) {
  4842. ValCtx.EmitFormatError(ValidationRule::SmMaxTheadGroup,
  4843. {std::to_string(threadsInGroup),
  4844. std::to_string(DXIL::kMaxMSASThreadsPerGroup)});
  4845. }
  4846. // type of threadID, thread group ID take care by DXIL operation overload
  4847. // check.
  4848. } else if (ShaderType == DXIL::ShaderKind::Domain) {
  4849. const auto &DS = props.ShaderProps.DS;
  4850. DXIL::TessellatorDomain domain = DS.domain;
  4851. if (domain >= DXIL::TessellatorDomain::LastEntry)
  4852. domain = DXIL::TessellatorDomain::Undefined;
  4853. unsigned inputControlPointCount = DS.inputControlPoints;
  4854. if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  4855. ValCtx.EmitFormatError(
  4856. ValidationRule::SmDSInputControlPointCountRange,
  4857. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  4858. std::to_string(inputControlPointCount)});
  4859. }
  4860. if (domain == DXIL::TessellatorDomain::Undefined) {
  4861. ValCtx.EmitError(ValidationRule::SmValidDomain);
  4862. }
  4863. CheckPatchConstantSemantic(ValCtx, entryProps, Status);
  4864. } else if (ShaderType == DXIL::ShaderKind::Hull) {
  4865. const auto &HS = props.ShaderProps.HS;
  4866. DXIL::TessellatorDomain domain = HS.domain;
  4867. if (domain >= DXIL::TessellatorDomain::LastEntry)
  4868. domain = DXIL::TessellatorDomain::Undefined;
  4869. unsigned inputControlPointCount = HS.inputControlPoints;
  4870. if (inputControlPointCount == 0) {
  4871. const DxilSignature &inputSig = entryProps.sig.InputSignature;
  4872. if (!inputSig.GetElements().empty()) {
  4873. ValCtx.EmitError(ValidationRule::SmZeroHSInputControlPointWithInput);
  4874. }
  4875. } else if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  4876. ValCtx.EmitFormatError(
  4877. ValidationRule::SmHSInputControlPointCountRange,
  4878. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  4879. std::to_string(inputControlPointCount)});
  4880. }
  4881. unsigned outputControlPointCount = HS.outputControlPoints;
  4882. if (outputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  4883. ValCtx.EmitFormatError(
  4884. ValidationRule::SmOutputControlPointCountRange,
  4885. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  4886. std::to_string(outputControlPointCount)});
  4887. }
  4888. if (domain == DXIL::TessellatorDomain::Undefined) {
  4889. ValCtx.EmitError(ValidationRule::SmValidDomain);
  4890. }
  4891. DXIL::TessellatorPartitioning partition = HS.partition;
  4892. if (partition == DXIL::TessellatorPartitioning::Undefined) {
  4893. ValCtx.EmitError(ValidationRule::MetaTessellatorPartition);
  4894. }
  4895. DXIL::TessellatorOutputPrimitive tessOutputPrimitive = HS.outputPrimitive;
  4896. if (tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::Undefined ||
  4897. tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::LastEntry) {
  4898. ValCtx.EmitError(ValidationRule::MetaTessellatorOutputPrimitive);
  4899. }
  4900. float maxTessFactor = HS.maxTessFactor;
  4901. if (maxTessFactor < DXIL::kHSMaxTessFactorLowerBound ||
  4902. maxTessFactor > DXIL::kHSMaxTessFactorUpperBound) {
  4903. ValCtx.EmitFormatError(ValidationRule::MetaMaxTessFactor,
  4904. {std::to_string(DXIL::kHSMaxTessFactorLowerBound),
  4905. std::to_string(DXIL::kHSMaxTessFactorUpperBound),
  4906. std::to_string(maxTessFactor)});
  4907. }
  4908. // Domain and OutPrimivtive match.
  4909. switch (domain) {
  4910. case DXIL::TessellatorDomain::IsoLine:
  4911. switch (tessOutputPrimitive) {
  4912. case DXIL::TessellatorOutputPrimitive::TriangleCW:
  4913. case DXIL::TessellatorOutputPrimitive::TriangleCCW:
  4914. ValCtx.EmitError(ValidationRule::SmIsoLineOutputPrimitiveMismatch);
  4915. break;
  4916. default:
  4917. break;
  4918. }
  4919. break;
  4920. case DXIL::TessellatorDomain::Tri:
  4921. switch (tessOutputPrimitive) {
  4922. case DXIL::TessellatorOutputPrimitive::Line:
  4923. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  4924. break;
  4925. default:
  4926. break;
  4927. }
  4928. break;
  4929. case DXIL::TessellatorDomain::Quad:
  4930. switch (tessOutputPrimitive) {
  4931. case DXIL::TessellatorOutputPrimitive::Line:
  4932. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  4933. break;
  4934. default:
  4935. break;
  4936. }
  4937. break;
  4938. default:
  4939. ValCtx.EmitError(ValidationRule::SmValidDomain);
  4940. break;
  4941. }
  4942. CheckPatchConstantSemantic(ValCtx, entryProps, Status);
  4943. } else if (ShaderType == DXIL::ShaderKind::Geometry) {
  4944. const auto &GS = props.ShaderProps.GS;
  4945. unsigned maxVertexCount = GS.maxVertexCount;
  4946. if (maxVertexCount > DXIL::kMaxGSOutputVertexCount) {
  4947. ValCtx.EmitFormatError(ValidationRule::SmGSOutputVertexCountRange,
  4948. {std::to_string(DXIL::kMaxGSOutputVertexCount),
  4949. std::to_string(maxVertexCount)});
  4950. }
  4951. unsigned instanceCount = GS.instanceCount;
  4952. if (instanceCount > DXIL::kMaxGSInstanceCount || instanceCount < 1) {
  4953. ValCtx.EmitFormatError(ValidationRule::SmGSInstanceCountRange,
  4954. {std::to_string(DXIL::kMaxGSInstanceCount),
  4955. std::to_string(instanceCount)});
  4956. }
  4957. DXIL::PrimitiveTopology topo = DXIL::PrimitiveTopology::Undefined;
  4958. bool bTopoMismatch = false;
  4959. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  4960. if (GS.streamPrimitiveTopologies[i] !=
  4961. DXIL::PrimitiveTopology::Undefined) {
  4962. if (topo == DXIL::PrimitiveTopology::Undefined)
  4963. topo = GS.streamPrimitiveTopologies[i];
  4964. else if (topo != GS.streamPrimitiveTopologies[i]) {
  4965. bTopoMismatch = true;
  4966. break;
  4967. }
  4968. }
  4969. }
  4970. if (bTopoMismatch)
  4971. topo = DXIL::PrimitiveTopology::Undefined;
  4972. switch (topo) {
  4973. case DXIL::PrimitiveTopology::PointList:
  4974. case DXIL::PrimitiveTopology::LineStrip:
  4975. case DXIL::PrimitiveTopology::TriangleStrip:
  4976. break;
  4977. default: {
  4978. ValCtx.EmitError(ValidationRule::SmGSValidOutputPrimitiveTopology);
  4979. } break;
  4980. }
  4981. DXIL::InputPrimitive inputPrimitive = GS.inputPrimitive;
  4982. unsigned VertexCount = GetNumVertices(inputPrimitive);
  4983. if (VertexCount == 0 && inputPrimitive != DXIL::InputPrimitive::Undefined) {
  4984. ValCtx.EmitError(ValidationRule::SmGSValidInputPrimitive);
  4985. }
  4986. }
  4987. }
  4988. static void ValidateShaderState(ValidationContext &ValCtx) {
  4989. DxilModule &DM = ValCtx.DxilMod;
  4990. if (ValCtx.isLibProfile) {
  4991. for (Function &F : DM.GetModule()->functions()) {
  4992. if (DM.HasDxilEntryProps(&F)) {
  4993. DxilEntryProps &entryProps = DM.GetDxilEntryProps(&F);
  4994. EntryStatus &Status = ValCtx.GetEntryStatus(&F);
  4995. ValidateEntryProps(ValCtx, entryProps, Status);
  4996. ValidatePassThruHS(ValCtx, entryProps, &F);
  4997. }
  4998. }
  4999. } else {
  5000. Function *Entry = DM.GetEntryFunction();
  5001. if (!DM.HasDxilEntryProps(Entry)) {
  5002. // must have props.
  5003. ValCtx.EmitError(ValidationRule::MetaNoEntryPropsForEntry);
  5004. return;
  5005. }
  5006. EntryStatus &Status = ValCtx.GetEntryStatus(Entry);
  5007. DxilEntryProps &entryProps = DM.GetDxilEntryProps(Entry);
  5008. ValidateEntryProps(ValCtx, entryProps, Status);
  5009. ValidatePassThruHS(ValCtx, entryProps, Entry);
  5010. }
  5011. }
  5012. static bool
  5013. CalculateCallDepth(CallGraphNode *node,
  5014. std::unordered_map<CallGraphNode *, unsigned> &depthMap,
  5015. std::unordered_set<CallGraphNode *> &callStack,
  5016. std::unordered_set<Function *> &funcSet) {
  5017. unsigned depth = callStack.size();
  5018. funcSet.insert(node->getFunction());
  5019. for (auto it = node->begin(), ei = node->end(); it != ei; it++) {
  5020. CallGraphNode *toNode = it->second;
  5021. if (callStack.insert(toNode).second == false) {
  5022. // Recursive.
  5023. return true;
  5024. }
  5025. if (depthMap[toNode] < depth)
  5026. depthMap[toNode] = depth;
  5027. if (CalculateCallDepth(toNode, depthMap, callStack, funcSet)) {
  5028. // Recursive
  5029. return true;
  5030. }
  5031. callStack.erase(toNode);
  5032. }
  5033. return false;
  5034. }
  5035. static void ValidateCallGraph(ValidationContext &ValCtx) {
  5036. // Build CallGraph.
  5037. CallGraph CG(*ValCtx.DxilMod.GetModule());
  5038. std::unordered_map<CallGraphNode*, unsigned> depthMap;
  5039. std::unordered_set<CallGraphNode*> callStack;
  5040. CallGraphNode *entryNode = CG[ValCtx.DxilMod.GetEntryFunction()];
  5041. depthMap[entryNode] = 0;
  5042. bool bRecursive = CalculateCallDepth(entryNode, depthMap, callStack, ValCtx.entryFuncCallSet);
  5043. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  5044. CallGraphNode *patchConstantNode = CG[ValCtx.DxilMod.GetPatchConstantFunction()];
  5045. depthMap[patchConstantNode] = 0;
  5046. callStack.clear();
  5047. bRecursive |= CalculateCallDepth(patchConstantNode, depthMap, callStack, ValCtx.patchConstFuncCallSet);
  5048. }
  5049. if (bRecursive) {
  5050. ValCtx.EmitError(ValidationRule::FlowNoRecusion);
  5051. }
  5052. }
  5053. static void ValidateFlowControl(ValidationContext &ValCtx) {
  5054. bool reducible =
  5055. IsReducible(*ValCtx.DxilMod.GetModule(), IrreducibilityAction::Ignore);
  5056. if (!reducible) {
  5057. ValCtx.EmitError(ValidationRule::FlowReducible);
  5058. return;
  5059. }
  5060. ValidateCallGraph(ValCtx);
  5061. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  5062. if (F.isDeclaration())
  5063. continue;
  5064. DominatorTreeAnalysis DTA;
  5065. DominatorTree DT = DTA.run(F);
  5066. LoopInfo LI;
  5067. LI.Analyze(DT);
  5068. for (auto loopIt = LI.begin(); loopIt != LI.end(); loopIt++) {
  5069. Loop *loop = *loopIt;
  5070. SmallVector<BasicBlock *, 4> exitBlocks;
  5071. loop->getExitBlocks(exitBlocks);
  5072. if (exitBlocks.empty())
  5073. ValCtx.EmitError(ValidationRule::FlowDeadLoop);
  5074. }
  5075. }
  5076. // fxc has ERR_CONTINUE_INSIDE_SWITCH to disallow continue in switch.
  5077. // Not do it for now.
  5078. }
  5079. static void ValidateUninitializedOutput(ValidationContext &ValCtx,
  5080. const DxilEntryProps &entryProps,
  5081. EntryStatus &Status) {
  5082. const DxilFunctionProps &props = entryProps.props;
  5083. // For HS only need to check Tessfactor which is in patch constant sig.
  5084. if (props.IsHS()) {
  5085. std::vector<unsigned> &patchConstOrPrimCols = Status.patchConstOrPrimCols;
  5086. const DxilSignature &patchConstSig = entryProps.sig.PatchConstOrPrimSignature;
  5087. for (auto &E : patchConstSig.GetElements()) {
  5088. unsigned mask = patchConstOrPrimCols[E->GetID()];
  5089. unsigned requireMask = (1 << E->GetCols()) - 1;
  5090. // TODO: check other case uninitialized output is allowed.
  5091. if (mask != requireMask && !E->GetSemantic()->IsArbitrary()) {
  5092. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput,
  5093. {E->GetName()});
  5094. }
  5095. }
  5096. return;
  5097. }
  5098. const DxilSignature &outSig = entryProps.sig.OutputSignature;
  5099. std::vector<unsigned> &outputCols = Status.outputCols;
  5100. for (auto &E : outSig.GetElements()) {
  5101. unsigned mask = outputCols[E->GetID()];
  5102. unsigned requireMask = (1 << E->GetCols()) - 1;
  5103. // TODO: check other case uninitialized output is allowed.
  5104. if (mask != requireMask && !E->GetSemantic()->IsArbitrary() &&
  5105. E->GetSemantic()->GetKind() != Semantic::Kind::Target) {
  5106. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput, {E->GetName()});
  5107. }
  5108. }
  5109. if (!props.IsGS()) {
  5110. unsigned posMask = Status.OutputPositionMask[0];
  5111. if (posMask != 0xf && Status.hasOutputPosition[0]) {
  5112. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  5113. }
  5114. } else {
  5115. const auto &GS = props.ShaderProps.GS;
  5116. unsigned streamMask = 0;
  5117. for (size_t i = 0; i < _countof(GS.streamPrimitiveTopologies); ++i) {
  5118. if (GS.streamPrimitiveTopologies[i] !=
  5119. DXIL::PrimitiveTopology::Undefined) {
  5120. streamMask |= 1<<i;
  5121. }
  5122. }
  5123. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  5124. if (streamMask & (1 << i)) {
  5125. unsigned posMask = Status.OutputPositionMask[i];
  5126. if (posMask != 0xf && Status.hasOutputPosition[i]) {
  5127. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  5128. }
  5129. }
  5130. }
  5131. }
  5132. }
  5133. static void ValidateUninitializedOutput(ValidationContext &ValCtx) {
  5134. DxilModule &DM = ValCtx.DxilMod;
  5135. if (ValCtx.isLibProfile) {
  5136. for (Function &F : DM.GetModule()->functions()) {
  5137. if (DM.HasDxilEntryProps(&F)) {
  5138. DxilEntryProps &entryProps = DM.GetDxilEntryProps(&F);
  5139. EntryStatus &Status = ValCtx.GetEntryStatus(&F);
  5140. ValidateUninitializedOutput(ValCtx, entryProps, Status);
  5141. }
  5142. }
  5143. } else {
  5144. Function *Entry = DM.GetEntryFunction();
  5145. if (!DM.HasDxilEntryProps(Entry)) {
  5146. // must have props.
  5147. ValCtx.EmitError(ValidationRule::MetaNoEntryPropsForEntry);
  5148. return;
  5149. }
  5150. EntryStatus &Status = ValCtx.GetEntryStatus(Entry);
  5151. DxilEntryProps &entryProps = DM.GetDxilEntryProps(Entry);
  5152. ValidateUninitializedOutput(ValCtx, entryProps, Status);
  5153. }
  5154. }
  5155. void GetValidationVersion(_Out_ unsigned *pMajor, _Out_ unsigned *pMinor) {
  5156. /* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_validation_version()</py>*/
  5157. // VALRULE-TEXT:BEGIN
  5158. // 1.0 is the first validator.
  5159. // 1.1 adds:
  5160. // - ILDN container part support
  5161. // 1.2 adds:
  5162. // - Metadata for floating point denorm mode
  5163. // 1.3 adds:
  5164. // - Library support
  5165. // - Raytracing support
  5166. // - i64/f64 overloads for rawBufferLoad/Store
  5167. // 1.4 adds:
  5168. // - packed u8x4/i8x4 dot with accumulate to i32
  5169. // - half dot2 with accumulate to float
  5170. // 1.5 adds:
  5171. // - WaveMatch, WaveMultiPrefixOp, WaveMultiPrefixBitCount
  5172. // - HASH container part support
  5173. // - Mesh and Amplification shaders
  5174. // - DXR 1.1 & RayQuery support
  5175. *pMajor = 1;
  5176. *pMinor = 6;
  5177. // VALRULE-TEXT:END
  5178. }
  5179. _Use_decl_annotations_ HRESULT
  5180. ValidateDxilModule(llvm::Module *pModule, llvm::Module *pDebugModule) {
  5181. std::string diagStr;
  5182. raw_string_ostream diagStream(diagStr);
  5183. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  5184. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  5185. if (!pDxilModule) {
  5186. return DXC_E_IR_VERIFICATION_FAILED;
  5187. }
  5188. if (pDxilModule->HasMetadataErrors()) {
  5189. DiagPrinter << "Metadata error encountered in non-critical metadata (such as Type Annotations).\n";
  5190. return DXC_E_IR_VERIFICATION_FAILED;
  5191. }
  5192. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  5193. ValidateBitcode(ValCtx);
  5194. ValidateMetadata(ValCtx);
  5195. ValidateShaderState(ValCtx);
  5196. ValidateGlobalVariables(ValCtx);
  5197. ValidateResources(ValCtx);
  5198. // Validate control flow and collect function call info.
  5199. // If has recursive call, call info collection will not finish.
  5200. ValidateFlowControl(ValCtx);
  5201. // Validate functions.
  5202. for (Function &F : pModule->functions()) {
  5203. ValidateFunction(F, ValCtx);
  5204. }
  5205. ValidateShaderFlags(ValCtx);
  5206. ValidateEntrySignatures(ValCtx);
  5207. ValidateUninitializedOutput(ValCtx);
  5208. // Ensure error messages are flushed out on error.
  5209. if (ValCtx.Failed) {
  5210. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  5211. return DXC_E_IR_VERIFICATION_FAILED;
  5212. }
  5213. return S_OK;
  5214. }
  5215. // DXIL Container Verification Functions
  5216. static void VerifyBlobPartMatches(_In_ ValidationContext &ValCtx,
  5217. _In_ LPCSTR pName,
  5218. DxilPartWriter *pWriter,
  5219. _In_reads_bytes_opt_(Size) const void *pData,
  5220. _In_ uint32_t Size) {
  5221. if (!pData && pWriter->size()) {
  5222. // No blob part, but writer says non-zero size is expected.
  5223. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {pName});
  5224. return;
  5225. }
  5226. // Compare sizes
  5227. if (pWriter->size() != Size) {
  5228. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  5229. return;
  5230. }
  5231. if (Size == 0) {
  5232. return;
  5233. }
  5234. CComPtr<AbstractMemoryStream> pOutputStream;
  5235. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  5236. pOutputStream->Reserve(Size);
  5237. pWriter->write(pOutputStream);
  5238. DXASSERT(pOutputStream->GetPtrSize() == Size, "otherwise, DxilPartWriter misreported size");
  5239. if (memcmp(pData, pOutputStream->GetPtr(), Size)) {
  5240. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  5241. return;
  5242. }
  5243. return;
  5244. }
  5245. static void VerifySignatureMatches(_In_ ValidationContext &ValCtx,
  5246. DXIL::SignatureKind SigKind,
  5247. _In_reads_bytes_opt_(SigSize) const void *pSigData,
  5248. _In_ uint32_t SigSize) {
  5249. // Generate corresponding signature from module and memcmp
  5250. const char *pName = nullptr;
  5251. switch (SigKind)
  5252. {
  5253. case hlsl::DXIL::SignatureKind::Input:
  5254. pName = "Program Input Signature";
  5255. break;
  5256. case hlsl::DXIL::SignatureKind::Output:
  5257. pName = "Program Output Signature";
  5258. break;
  5259. case hlsl::DXIL::SignatureKind::PatchConstOrPrim:
  5260. if (ValCtx.DxilMod.GetShaderModel()->GetKind() == DXIL::ShaderKind::Mesh)
  5261. pName = "Program Primitive Signature";
  5262. else
  5263. pName = "Program Patch Constant Signature";
  5264. break;
  5265. default:
  5266. break;
  5267. }
  5268. unique_ptr<DxilPartWriter> pWriter(NewProgramSignatureWriter(ValCtx.DxilMod, SigKind));
  5269. VerifyBlobPartMatches(ValCtx, pName, pWriter.get(), pSigData, SigSize);
  5270. }
  5271. _Use_decl_annotations_
  5272. bool VerifySignatureMatches(llvm::Module *pModule,
  5273. DXIL::SignatureKind SigKind,
  5274. const void *pSigData,
  5275. uint32_t SigSize) {
  5276. std::string diagStr;
  5277. raw_string_ostream diagStream(diagStr);
  5278. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  5279. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  5280. VerifySignatureMatches(ValCtx, SigKind, pSigData, SigSize);
  5281. if (ValCtx.Failed) {
  5282. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  5283. }
  5284. return !ValCtx.Failed;
  5285. }
  5286. static void VerifyPSVMatches(_In_ ValidationContext &ValCtx,
  5287. _In_reads_bytes_(PSVSize) const void *pPSVData,
  5288. _In_ uint32_t PSVSize) {
  5289. uint32_t PSVVersion = 1; // This should be set to the newest version
  5290. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  5291. // Try each version in case an earlier version matches module
  5292. while (PSVVersion && pWriter->size() != PSVSize) {
  5293. PSVVersion --;
  5294. pWriter.reset(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  5295. }
  5296. // generate PSV data from module and memcmp
  5297. VerifyBlobPartMatches(ValCtx, "Pipeline State Validation", pWriter.get(), pPSVData, PSVSize);
  5298. }
  5299. _Use_decl_annotations_
  5300. bool VerifyPSVMatches(llvm::Module *pModule,
  5301. const void *pPSVData,
  5302. uint32_t PSVSize) {
  5303. std::string diagStr;
  5304. raw_string_ostream diagStream(diagStr);
  5305. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  5306. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  5307. VerifyPSVMatches(ValCtx, pPSVData, PSVSize);
  5308. if (ValCtx.Failed) {
  5309. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  5310. }
  5311. return !ValCtx.Failed;
  5312. }
  5313. static void VerifyFeatureInfoMatches(_In_ ValidationContext &ValCtx,
  5314. _In_reads_bytes_(FeatureInfoSize) const void *pFeatureInfoData,
  5315. _In_ uint32_t FeatureInfoSize) {
  5316. // generate Feature Info data from module and memcmp
  5317. unique_ptr<DxilPartWriter> pWriter(NewFeatureInfoWriter(ValCtx.DxilMod));
  5318. VerifyBlobPartMatches(ValCtx, "Feature Info", pWriter.get(), pFeatureInfoData, FeatureInfoSize);
  5319. }
  5320. static void VerifyRDATMatches(_In_ ValidationContext &ValCtx,
  5321. _In_reads_bytes_(RDATSize) const void *pRDATData,
  5322. _In_ uint32_t RDATSize) {
  5323. const char *PartName = "Runtime Data (RDAT)";
  5324. // If DxilModule subobjects already loaded, validate these against the RDAT blob,
  5325. // otherwise, load subobject into DxilModule to generate reference RDAT.
  5326. if (!ValCtx.DxilMod.GetSubobjects()) {
  5327. RDAT::DxilRuntimeData rdat(pRDATData, RDATSize);
  5328. auto *pSubobjReader = rdat.GetSubobjectTableReader();
  5329. if (pSubobjReader && pSubobjReader->GetCount() > 0) {
  5330. ValCtx.DxilMod.ResetSubobjects(new DxilSubobjects());
  5331. if (!LoadSubobjectsFromRDAT(*ValCtx.DxilMod.GetSubobjects(), pSubobjReader)) {
  5332. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, { PartName });
  5333. return;
  5334. }
  5335. }
  5336. }
  5337. unique_ptr<DxilPartWriter> pWriter(NewRDATWriter(ValCtx.DxilMod, 0));
  5338. VerifyBlobPartMatches(ValCtx, PartName, pWriter.get(), pRDATData, RDATSize);
  5339. // Verify no errors when runtime reflection from RDAT:
  5340. RDAT::DxilRuntimeReflection *pReflection = RDAT::CreateDxilRuntimeReflection();
  5341. if (!pReflection->InitFromRDAT(pRDATData, RDATSize)) {
  5342. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, { PartName });
  5343. return;
  5344. }
  5345. }
  5346. _Use_decl_annotations_
  5347. bool VerifyRDATMatches(llvm::Module *pModule,
  5348. const void *pRDATData,
  5349. uint32_t RDATSize) {
  5350. std::string diagStr;
  5351. raw_string_ostream diagStream(diagStr);
  5352. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  5353. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  5354. VerifyRDATMatches(ValCtx, pRDATData, RDATSize);
  5355. if (ValCtx.Failed) {
  5356. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  5357. }
  5358. return !ValCtx.Failed;
  5359. }
  5360. _Use_decl_annotations_
  5361. bool VerifyFeatureInfoMatches(llvm::Module *pModule,
  5362. const void *pFeatureInfoData,
  5363. uint32_t FeatureInfoSize) {
  5364. std::string diagStr;
  5365. raw_string_ostream diagStream(diagStr);
  5366. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  5367. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  5368. VerifyFeatureInfoMatches(ValCtx, pFeatureInfoData, FeatureInfoSize);
  5369. if (ValCtx.Failed) {
  5370. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  5371. }
  5372. return !ValCtx.Failed;
  5373. }
  5374. _Use_decl_annotations_
  5375. HRESULT ValidateDxilContainerParts(llvm::Module *pModule,
  5376. llvm::Module *pDebugModule,
  5377. const DxilContainerHeader *pContainer,
  5378. uint32_t ContainerSize) {
  5379. DXASSERT_NOMSG(pModule);
  5380. if (!pContainer || !IsValidDxilContainer(pContainer, ContainerSize)) {
  5381. return DXC_E_CONTAINER_INVALID;
  5382. }
  5383. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  5384. if (!pDxilModule) {
  5385. return DXC_E_IR_VERIFICATION_FAILED;
  5386. }
  5387. std::string diagStr;
  5388. raw_string_ostream DiagStream(diagStr);
  5389. DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  5390. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  5391. DXIL::ShaderKind ShaderKind = pDxilModule->GetShaderModel()->GetKind();
  5392. bool bTessOrMesh = ShaderKind == DXIL::ShaderKind::Hull ||
  5393. ShaderKind == DXIL::ShaderKind::Domain ||
  5394. ShaderKind == DXIL::ShaderKind::Mesh;
  5395. std::unordered_set<uint32_t> FourCCFound;
  5396. const DxilPartHeader *pRootSignaturePart = nullptr;
  5397. const DxilPartHeader *pPSVPart = nullptr;
  5398. for (auto it = begin(pContainer), itEnd = end(pContainer); it != itEnd; ++it) {
  5399. const DxilPartHeader *pPart = *it;
  5400. char szFourCC[5];
  5401. PartKindToCharArray(pPart->PartFourCC, szFourCC);
  5402. if (FourCCFound.find(pPart->PartFourCC) != FourCCFound.end()) {
  5403. // Two parts with same FourCC found
  5404. ValCtx.EmitFormatError(ValidationRule::ContainerPartRepeated, {szFourCC});
  5405. continue;
  5406. }
  5407. FourCCFound.insert(pPart->PartFourCC);
  5408. switch (pPart->PartFourCC)
  5409. {
  5410. case DFCC_InputSignature:
  5411. if (ValCtx.isLibProfile) {
  5412. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5413. } else {
  5414. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, GetDxilPartData(pPart), pPart->PartSize);
  5415. }
  5416. break;
  5417. case DFCC_OutputSignature:
  5418. if (ValCtx.isLibProfile) {
  5419. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5420. } else {
  5421. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, GetDxilPartData(pPart), pPart->PartSize);
  5422. }
  5423. break;
  5424. case DFCC_PatchConstantSignature:
  5425. if (ValCtx.isLibProfile) {
  5426. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5427. } else {
  5428. if (bTessOrMesh) {
  5429. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::PatchConstOrPrim, GetDxilPartData(pPart), pPart->PartSize);
  5430. } else {
  5431. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {"Program Patch Constant Signature"});
  5432. }
  5433. }
  5434. break;
  5435. case DFCC_FeatureInfo:
  5436. VerifyFeatureInfoMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  5437. break;
  5438. case DFCC_RootSignature:
  5439. pRootSignaturePart = pPart;
  5440. if (ValCtx.isLibProfile) {
  5441. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5442. }
  5443. break;
  5444. case DFCC_PipelineStateValidation:
  5445. pPSVPart = pPart;
  5446. if (ValCtx.isLibProfile) {
  5447. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5448. } else {
  5449. VerifyPSVMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  5450. }
  5451. break;
  5452. // Skip these
  5453. case DFCC_ResourceDef:
  5454. case DFCC_ShaderStatistics:
  5455. case DFCC_PrivateData:
  5456. case DFCC_DXIL:
  5457. case DFCC_ShaderDebugInfoDXIL:
  5458. case DFCC_ShaderDebugName:
  5459. continue;
  5460. case DFCC_ShaderHash:
  5461. if (pPart->PartSize != sizeof(DxilShaderHash)) {
  5462. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5463. }
  5464. break;
  5465. // Runtime Data (RDAT) for libraries
  5466. case DFCC_RuntimeData:
  5467. if (ValCtx.isLibProfile) {
  5468. VerifyRDATMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  5469. } else {
  5470. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, { szFourCC });
  5471. }
  5472. break;
  5473. case DFCC_Container:
  5474. default:
  5475. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, {szFourCC});
  5476. break;
  5477. }
  5478. }
  5479. // Verify required parts found
  5480. if (ValCtx.isLibProfile) {
  5481. if (FourCCFound.find(DFCC_RuntimeData) == FourCCFound.end()) {
  5482. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, { "Runtime Data (RDAT)" });
  5483. }
  5484. } else {
  5485. if (FourCCFound.find(DFCC_InputSignature) == FourCCFound.end()) {
  5486. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, nullptr, 0);
  5487. }
  5488. if (FourCCFound.find(DFCC_OutputSignature) == FourCCFound.end()) {
  5489. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, nullptr, 0);
  5490. }
  5491. if (bTessOrMesh && FourCCFound.find(DFCC_PatchConstantSignature) == FourCCFound.end() &&
  5492. pDxilModule->GetPatchConstOrPrimSignature().GetElements().size())
  5493. {
  5494. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, { "Program Patch Constant Signature" });
  5495. }
  5496. if (FourCCFound.find(DFCC_FeatureInfo) == FourCCFound.end()) {
  5497. // Could be optional, but RS1 runtime doesn't handle this case properly.
  5498. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, { "Feature Info" });
  5499. }
  5500. // Validate Root Signature
  5501. if (pPSVPart) {
  5502. if (pRootSignaturePart) {
  5503. try {
  5504. RootSignatureHandle RS;
  5505. RS.LoadSerialized((const uint8_t*)GetDxilPartData(pRootSignaturePart), pRootSignaturePart->PartSize);
  5506. RS.Deserialize();
  5507. IFTBOOL(VerifyRootSignatureWithShaderPSV(RS.GetDesc(),
  5508. pDxilModule->GetShaderModel()->GetKind(),
  5509. GetDxilPartData(pPSVPart), pPSVPart->PartSize,
  5510. DiagStream),
  5511. DXC_E_INCORRECT_ROOT_SIGNATURE);
  5512. } catch (...) {
  5513. ValCtx.EmitError(ValidationRule::ContainerRootSignatureIncompatible);
  5514. }
  5515. }
  5516. } else {
  5517. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Pipeline State Validation"});
  5518. }
  5519. }
  5520. if (ValCtx.Failed) {
  5521. emitDxilDiag(pModule->getContext(), DiagStream.str().c_str());
  5522. return DXC_E_MALFORMED_CONTAINER;
  5523. }
  5524. return S_OK;
  5525. }
  5526. static HRESULT FindDxilPart(_In_reads_bytes_(ContainerSize) const void *pContainerBytes,
  5527. _In_ uint32_t ContainerSize,
  5528. _In_ DxilFourCC FourCC,
  5529. _In_ const DxilPartHeader **ppPart) {
  5530. const DxilContainerHeader *pContainer =
  5531. IsDxilContainerLike(pContainerBytes, ContainerSize);
  5532. if (!pContainer) {
  5533. IFR(DXC_E_CONTAINER_INVALID);
  5534. }
  5535. if (!IsValidDxilContainer(pContainer, ContainerSize)) {
  5536. IFR(DXC_E_CONTAINER_INVALID);
  5537. }
  5538. DxilPartIterator it = std::find_if(begin(pContainer), end(pContainer),
  5539. DxilPartIsType(FourCC));
  5540. if (it == end(pContainer)) {
  5541. IFR(DXC_E_CONTAINER_MISSING_DXIL);
  5542. }
  5543. const DxilProgramHeader *pProgramHeader =
  5544. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it));
  5545. if (!IsValidDxilProgramHeader(pProgramHeader, (*it)->PartSize)) {
  5546. IFR(DXC_E_CONTAINER_INVALID);
  5547. }
  5548. *ppPart = *it;
  5549. return S_OK;
  5550. }
  5551. _Use_decl_annotations_
  5552. HRESULT ValidateLoadModule(const char *pIL,
  5553. uint32_t ILLength,
  5554. unique_ptr<llvm::Module> &pModule,
  5555. LLVMContext &Ctx,
  5556. llvm::raw_ostream &DiagStream,
  5557. unsigned bLazyLoad) {
  5558. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  5559. PrintDiagnosticContext DiagContext(DiagPrinter);
  5560. DiagRestore DR(Ctx, &DiagContext);
  5561. std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf;
  5562. pBitcodeBuf.reset(llvm::MemoryBuffer::getMemBuffer(
  5563. llvm::StringRef(pIL, ILLength), "", false).release());
  5564. ErrorOr<std::unique_ptr<Module>> loadedModuleResult =
  5565. bLazyLoad == 0?
  5566. llvm::parseBitcodeFile(pBitcodeBuf->getMemBufferRef(), Ctx, nullptr, true /*Track Bitstream*/) :
  5567. llvm::getLazyBitcodeModule(std::move(pBitcodeBuf), Ctx, nullptr, false, true /*Track Bitstream*/);
  5568. // DXIL disallows some LLVM bitcode constructs, like unaccounted-for sub-blocks.
  5569. // These appear as warnings, which the validator should reject.
  5570. if (DiagContext.HasErrors() || DiagContext.HasWarnings() || loadedModuleResult.getError())
  5571. return DXC_E_IR_VERIFICATION_FAILED;
  5572. pModule = std::move(loadedModuleResult.get());
  5573. return S_OK;
  5574. }
  5575. HRESULT ValidateDxilBitcode(
  5576. _In_reads_bytes_(ILLength) const char *pIL,
  5577. _In_ uint32_t ILLength,
  5578. _In_ llvm::raw_ostream &DiagStream) {
  5579. LLVMContext Ctx;
  5580. std::unique_ptr<llvm::Module> pModule;
  5581. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  5582. PrintDiagnosticContext DiagContext(DiagPrinter);
  5583. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  5584. &DiagContext, true);
  5585. HRESULT hr;
  5586. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream,
  5587. /*bLazyLoad*/ false)))
  5588. return hr;
  5589. if (FAILED(hr = ValidateDxilModule(pModule.get(), nullptr)))
  5590. return hr;
  5591. DxilModule &dxilModule = pModule->GetDxilModule();
  5592. auto &SerializedRootSig = dxilModule.GetSerializedRootSignature();
  5593. if (!SerializedRootSig.empty()) {
  5594. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(dxilModule, 0));
  5595. DXASSERT_NOMSG(pWriter->size());
  5596. CComPtr<AbstractMemoryStream> pOutputStream;
  5597. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  5598. pOutputStream->Reserve(pWriter->size());
  5599. pWriter->write(pOutputStream);
  5600. try {
  5601. const DxilVersionedRootSignatureDesc* pDesc = nullptr;
  5602. DeserializeRootSignature(SerializedRootSig.data(), SerializedRootSig.size(), &pDesc);
  5603. if (!pDesc) {
  5604. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  5605. }
  5606. IFTBOOL(VerifyRootSignatureWithShaderPSV(pDesc,
  5607. dxilModule.GetShaderModel()->GetKind(),
  5608. pOutputStream->GetPtr(), pWriter->size(),
  5609. DiagStream), DXC_E_INCORRECT_ROOT_SIGNATURE);
  5610. } catch (...) {
  5611. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  5612. }
  5613. }
  5614. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  5615. return DXC_E_IR_VERIFICATION_FAILED;
  5616. }
  5617. return S_OK;
  5618. }
  5619. static HRESULT ValidateLoadModuleFromContainer(
  5620. _In_reads_bytes_(ILLength) const void *pContainer,
  5621. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  5622. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  5623. _In_ llvm::LLVMContext &Ctx, LLVMContext &DbgCtx,
  5624. _In_ llvm::raw_ostream &DiagStream, _In_ unsigned bLazyLoad) {
  5625. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  5626. PrintDiagnosticContext DiagContext(DiagPrinter);
  5627. DiagRestore DR(Ctx, &DiagContext);
  5628. DiagRestore DR2(DbgCtx, &DiagContext);
  5629. const DxilPartHeader *pPart = nullptr;
  5630. IFR(FindDxilPart(pContainer, ContainerSize, DFCC_DXIL, &pPart));
  5631. const char *pIL = nullptr;
  5632. uint32_t ILLength = 0;
  5633. GetDxilProgramBitcode(
  5634. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pPart)), &pIL,
  5635. &ILLength);
  5636. IFR(ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream, bLazyLoad));
  5637. HRESULT hr;
  5638. const DxilPartHeader *pDbgPart = nullptr;
  5639. if (FAILED(hr = FindDxilPart(pContainer, ContainerSize,
  5640. DFCC_ShaderDebugInfoDXIL, &pDbgPart)) &&
  5641. hr != DXC_E_CONTAINER_MISSING_DXIL) {
  5642. return hr;
  5643. }
  5644. if (pDbgPart) {
  5645. GetDxilProgramBitcode(
  5646. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pDbgPart)),
  5647. &pIL, &ILLength);
  5648. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pDebugModule, DbgCtx,
  5649. DiagStream, bLazyLoad))) {
  5650. return hr;
  5651. }
  5652. }
  5653. return S_OK;
  5654. }
  5655. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainer(
  5656. _In_reads_bytes_(ContainerSize) const void *pContainer,
  5657. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  5658. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  5659. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  5660. _In_ llvm::raw_ostream &DiagStream) {
  5661. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  5662. pDebugModule, Ctx, DbgCtx, DiagStream,
  5663. /*bLazyLoad*/ false);
  5664. }
  5665. // Lazy loads module from container, validating load, but not module.
  5666. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainerLazy(
  5667. _In_reads_bytes_(ContainerSize) const void *pContainer,
  5668. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  5669. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  5670. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  5671. _In_ llvm::raw_ostream &DiagStream) {
  5672. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  5673. pDebugModule, Ctx, DbgCtx, DiagStream,
  5674. /*bLazyLoad*/ true);
  5675. }
  5676. _Use_decl_annotations_
  5677. HRESULT ValidateDxilContainer(const void *pContainer,
  5678. uint32_t ContainerSize,
  5679. llvm::raw_ostream &DiagStream) {
  5680. LLVMContext Ctx, DbgCtx;
  5681. std::unique_ptr<llvm::Module> pModule, pDebugModule;
  5682. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  5683. PrintDiagnosticContext DiagContext(DiagPrinter);
  5684. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  5685. &DiagContext, true);
  5686. DbgCtx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  5687. &DiagContext, true);
  5688. IFR(ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule, pDebugModule,
  5689. Ctx, DbgCtx, DiagStream));
  5690. // Validate DXIL Module
  5691. IFR(ValidateDxilModule(pModule.get(), pDebugModule.get()));
  5692. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  5693. return DXC_E_IR_VERIFICATION_FAILED;
  5694. }
  5695. return ValidateDxilContainerParts(pModule.get(), pDebugModule.get(),
  5696. IsDxilContainerLike(pContainer, ContainerSize), ContainerSize);
  5697. }
  5698. } // namespace hlsl