DxilValidation.cpp 245 KB

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