DxilValidation.cpp 249 KB

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