DxilValidation.cpp 184 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766
  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/HLSL/DxilValidation.h"
  12. #include "dxc/HLSL/DxilGenerationPass.h"
  13. #include "dxc/HLSL/DXILOperations.h"
  14. #include "dxc/HLSL/DxilModule.h"
  15. #include "dxc/HLSL/DxilShaderModel.h"
  16. #include "dxc/HLSL/DxilContainer.h"
  17. #include "dxc/Support/Global.h"
  18. #include "dxc/HLSL/DxilUtil.h"
  19. #include "dxc/HLSL/DxilInstructions.h"
  20. #include "dxc/HLSL/ReducibilityAnalysis.h"
  21. #include "dxc/Support/WinIncludes.h"
  22. #include "dxc/Support/FileIOHelper.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/Analysis/CallGraph.h"
  25. #include "llvm/IR/LLVMContext.h"
  26. #include "llvm/IR/Module.h"
  27. #include "llvm/IR/Type.h"
  28. #include "llvm/IR/Operator.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/InstIterator.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/DiagnosticInfo.h"
  33. #include "llvm/IR/DiagnosticPrinter.h"
  34. #include "llvm/ADT/BitVector.h"
  35. #include "llvm/Support/raw_ostream.h"
  36. #include "llvm/Support/MemoryBuffer.h"
  37. #include "llvm/Bitcode/ReaderWriter.h"
  38. #include <unordered_set>
  39. #include "llvm/Analysis/LoopInfo.h"
  40. #include "llvm/IR/Dominators.h"
  41. #include "llvm/Analysis/PostDominators.h"
  42. #include "dxc/HLSL/DxilSpanAllocator.h"
  43. #include "dxc/HLSL/DxilSignatureAllocator.h"
  44. #include "dxc/HLSL/DxilRootSignature.h"
  45. #include <algorithm>
  46. using namespace llvm;
  47. using namespace std;
  48. ///////////////////////////////////////////////////////////////////////////////
  49. // Error messages.
  50. const char *hlsl::GetValidationRuleText(ValidationRule value) {
  51. /* <py::lines('VALRULE-TEXT')>hctdb_instrhelp.get_valrule_text()</py>*/
  52. // VALRULE-TEXT:BEGIN
  53. switch(value) {
  54. case hlsl::ValidationRule::BitcodeValid: return "Module bitcode is invalid";
  55. case hlsl::ValidationRule::ContainerPartMatches: return "Container part '%0' does not match expected for module.";
  56. case hlsl::ValidationRule::ContainerPartRepeated: return "More than one container part '%0'.";
  57. case hlsl::ValidationRule::ContainerPartMissing: return "Missing part '%0' required by module.";
  58. case hlsl::ValidationRule::ContainerPartInvalid: return "Unknown part '%0' found in DXIL container.";
  59. case hlsl::ValidationRule::ContainerRootSignatureIncompatible: return "Root Signature in DXIL container is not compatible with shader.";
  60. case hlsl::ValidationRule::MetaRequired: return "TODO - Required metadata missing";
  61. case hlsl::ValidationRule::MetaKnown: return "Named metadata '%0' is unknown";
  62. case hlsl::ValidationRule::MetaUsed: return "All metadata must be used by dxil";
  63. case hlsl::ValidationRule::MetaTarget: return "Unknown target triple '%0'";
  64. case hlsl::ValidationRule::MetaWellFormed: return "TODO - Metadata must be well-formed in operand count and types";
  65. case hlsl::ValidationRule::MetaSemanticLen: return "Semantic length must be at least 1 and at most 64";
  66. case hlsl::ValidationRule::MetaInterpModeValid: return "Invalid interpolation mode for '%0'";
  67. case hlsl::ValidationRule::MetaSemaKindValid: return "Semantic kind for '%0' is invalid";
  68. case hlsl::ValidationRule::MetaNoSemanticOverlap: return "Semantic '%0' overlap at %1";
  69. case hlsl::ValidationRule::MetaSemaKindMatchesName: return "Semantic name %0 does not match System Value kind %1";
  70. case hlsl::ValidationRule::MetaDuplicateSysValue: return "System value %0 appears more than once in the same signature.";
  71. case hlsl::ValidationRule::MetaSemanticIndexMax: return "%0 semantic index exceeds maximum (%1)";
  72. case hlsl::ValidationRule::MetaSystemValueRows: return "rows for system value semantic %0 must be 1";
  73. case hlsl::ValidationRule::MetaSemanticShouldBeAllocated: return "%0 Semantic '%1' should have a valid packing location";
  74. case hlsl::ValidationRule::MetaSemanticShouldNotBeAllocated: return "%0 Semantic '%1' should have a packing location of -1";
  75. case hlsl::ValidationRule::MetaValueRange: return "Metadata value must be within range";
  76. case hlsl::ValidationRule::MetaFlagsUsage: return "Flags must match usage";
  77. case hlsl::ValidationRule::MetaDenseResIDs: return "Resource identifiers must be zero-based and dense";
  78. case hlsl::ValidationRule::MetaSignatureOverlap: return "signature element %0 at location (%1,%2) size (%3,%4) overlaps another signature element.";
  79. case hlsl::ValidationRule::MetaSignatureOutOfRange: return "signature element %0 at location (%1,%2) size (%3,%4) is out of range.";
  80. 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.";
  81. case hlsl::ValidationRule::MetaSignatureIllegalComponentOrder: return "signature element %0 at location (%1,%2) size (%3,%4) violates component ordering rule (arb < sv < sgv).";
  82. 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.";
  83. case hlsl::ValidationRule::MetaIntegerInterpMode: return "signature element %0 specifies invalid interpolation mode for integer component type.";
  84. 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.";
  85. case hlsl::ValidationRule::MetaSemanticCompType: return "%0 must be %1";
  86. case hlsl::ValidationRule::MetaClipCullMaxRows: return "ClipDistance and CullDistance occupy more than the maximum of 2 rows combined.";
  87. case hlsl::ValidationRule::MetaClipCullMaxComponents: return "ClipDistance and CullDistance use more than the maximum of 8 components combined.";
  88. case hlsl::ValidationRule::MetaSignatureCompType: return "signature %0 specifies unrecognized or invalid component type";
  89. case hlsl::ValidationRule::MetaTessellatorPartition: return "Invalid Tessellator Partitioning specified. Must be integer, pow2, fractional_odd or fractional_even.";
  90. case hlsl::ValidationRule::MetaTessellatorOutputPrimitive: return "Invalid Tessellator Output Primitive specified. Must be point, line, triangleCW or triangleCCW.";
  91. case hlsl::ValidationRule::MetaMaxTessFactor: return "Hull Shader MaxTessFactor must be [%0..%1]. %2 specified";
  92. case hlsl::ValidationRule::MetaValidSamplerMode: return "Invalid sampler mode on sampler ";
  93. case hlsl::ValidationRule::MetaFunctionAnnotation: return "Cannot find function annotation for %0";
  94. case hlsl::ValidationRule::MetaGlcNotOnAppendConsume: return "globallycoherent cannot be used with append/consume buffers";
  95. case hlsl::ValidationRule::MetaStructBufAlignment: return "structured buffer element size must be a multiple of %0 bytes (actual size %1 bytes)";
  96. case hlsl::ValidationRule::MetaStructBufAlignmentOutOfBound: return "structured buffer elements cannot be larger than %0 bytes (actual size %1 bytes)";
  97. case hlsl::ValidationRule::MetaEntryFunction: return "entrypoint not found";
  98. case hlsl::ValidationRule::MetaInvalidControlFlowHint: return "Invalid control flow hint";
  99. case hlsl::ValidationRule::MetaBranchFlatten: return "Can't use branch and flatten attributes together";
  100. case hlsl::ValidationRule::MetaForceCaseOnSwitch: return "Attribute forcecase only works for switch";
  101. case hlsl::ValidationRule::MetaControlFlowHintNotOnControlFlow: return "Control flow hint only works on control flow inst";
  102. case hlsl::ValidationRule::MetaTextureType: return "elements of typed buffers and textures must fit in four 32-bit quantities";
  103. case hlsl::ValidationRule::MetaBarycentricsInterpolation: return "SV_Barycentrics cannot be used with 'nointerpolation' type";
  104. case hlsl::ValidationRule::MetaBarycentricsFloat3: return "only 'float3' type is allowed for SV_Barycentrics.";
  105. case hlsl::ValidationRule::MetaBarycentricsTwoPerspectives: return "There can only be up to two input attributes of SV_Barycentrics with different perspective interpolation mode.";
  106. case hlsl::ValidationRule::InstrOload: return "DXIL intrinsic overload must be valid";
  107. case hlsl::ValidationRule::InstrCallOload: return "Call to DXIL intrinsic '%0' does not match an allowed overload signature";
  108. case hlsl::ValidationRule::InstrPtrBitCast: return "Pointer type bitcast must be have same size";
  109. case hlsl::ValidationRule::InstrMinPrecisonBitCast: return "Bitcast on minprecison types is not allowed";
  110. case hlsl::ValidationRule::InstrStructBitCast: return "Bitcast on struct types is not allowed";
  111. case hlsl::ValidationRule::InstrStatus: return "Resource status should only used by CheckAccessFullyMapped";
  112. case hlsl::ValidationRule::InstrCheckAccessFullyMapped: return "CheckAccessFullyMapped should only used on resource status";
  113. case hlsl::ValidationRule::InstrOpConst: return "%0 of %1 must be an immediate constant";
  114. case hlsl::ValidationRule::InstrAllowed: return "Instructions must be of an allowed type";
  115. case hlsl::ValidationRule::InstrOpCodeReserved: return "Instructions must not reference reserved opcodes";
  116. case hlsl::ValidationRule::InstrOperandRange: return "expect %0 between %1, got %2";
  117. case hlsl::ValidationRule::InstrNoReadingUninitialized: return "Instructions should not read uninitialized value";
  118. case hlsl::ValidationRule::InstrNoGenericPtrAddrSpaceCast: return "Address space cast between pointer types must have one part to be generic address space";
  119. case hlsl::ValidationRule::InstrInBoundsAccess: return "Access to out-of-bounds memory is disallowed";
  120. case hlsl::ValidationRule::InstrOpConstRange: return "Constant values must be in-range for operation";
  121. case hlsl::ValidationRule::InstrImmBiasForSampleB: return "bias amount for sample_b must be in the range [%0,%1], but %2 was specified as an immediate";
  122. case hlsl::ValidationRule::InstrNoIndefiniteLog: return "No indefinite logarithm";
  123. case hlsl::ValidationRule::InstrNoIndefiniteAsin: return "No indefinite arcsine";
  124. case hlsl::ValidationRule::InstrNoIndefiniteAcos: return "No indefinite arccosine";
  125. case hlsl::ValidationRule::InstrNoIDivByZero: return "No signed integer division by zero";
  126. case hlsl::ValidationRule::InstrNoUDivByZero: return "No unsigned integer division by zero";
  127. case hlsl::ValidationRule::InstrNoIndefiniteDsxy: return "No indefinite derivative calculation";
  128. case hlsl::ValidationRule::InstrMinPrecisionNotPrecise: return "Instructions marked precise may not refer to minprecision values";
  129. case hlsl::ValidationRule::InstrOnlyOneAllocConsume: return "RWStructuredBuffers may increment or decrement their counters, but not both.";
  130. case hlsl::ValidationRule::InstrTextureOffset: return "offset texture instructions must take offset which can resolve to integer literal in the range -8 to 7";
  131. case hlsl::ValidationRule::InstrCannotPullPosition: return "%0 does not support pull-model evaluation of position";
  132. 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";
  133. case hlsl::ValidationRule::InstrResourceCoordinateMiss: return "coord uninitialized";
  134. case hlsl::ValidationRule::InstrResourceCoordinateTooMany: return "out of bound coord must be undef";
  135. case hlsl::ValidationRule::InstrResourceOffsetMiss: return "offset uninitialized";
  136. case hlsl::ValidationRule::InstrResourceOffsetTooMany: return "out of bound offset must be undef";
  137. case hlsl::ValidationRule::InstrUndefResultForGetDimension: return "GetDimensions used undef dimension %0 on %1";
  138. case hlsl::ValidationRule::InstrSamplerModeForLOD: return "lod instruction requires sampler declared in default mode";
  139. case hlsl::ValidationRule::InstrSamplerModeForSample: return "sample/_l/_d/_cl_s/gather instruction requires sampler declared in default mode";
  140. case hlsl::ValidationRule::InstrSamplerModeForSampleC: return "sample_c_*/gather_c instructions require sampler declared in comparison mode";
  141. case hlsl::ValidationRule::InstrSampleCompType: return "sample_* instructions require resource to be declared to return UNORM, SNORM or FLOAT.";
  142. case hlsl::ValidationRule::InstrBarrierModeUselessUGroup: return "sync can't specify both _ugroup and _uglobal. If both are needed, just specify _uglobal.";
  143. 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. ";
  144. case hlsl::ValidationRule::InstrBarrierModeForNonCS: return "sync in a non-Compute Shader must only sync UAV (sync_uglobal)";
  145. case hlsl::ValidationRule::InstrWriteMaskForTypedUAVStore: return "store on typed uav must write to all four components of the UAV";
  146. case hlsl::ValidationRule::InstrResourceKindForCalcLOD: return "lod requires resource declared as texture1D/2D/3D/Cube/CubeArray/1DArray/2DArray";
  147. case hlsl::ValidationRule::InstrResourceKindForSample: return "sample/_l/_d requires resource declared as texture1D/2D/3D/Cube/1DArray/2DArray/CubeArray";
  148. case hlsl::ValidationRule::InstrResourceKindForSampleC: return "samplec requires resource declared as texture1D/2D/Cube/1DArray/2DArray/CubeArray";
  149. case hlsl::ValidationRule::InstrResourceKindForGather: return "gather requires resource declared as texture/2D/Cube/2DArray/CubeArray";
  150. case hlsl::ValidationRule::InstrWriteMaskMatchValueForUAVStore: return "uav store write mask must match store value mask, write mask is %0 and store value mask is %1";
  151. case hlsl::ValidationRule::InstrResourceKindForBufferLoadStore: return "buffer load/store only works on Raw/Typed/StructuredBuffer";
  152. case hlsl::ValidationRule::InstrResourceKindForTextureStore: return "texture store only works on Texture1D/1DArray/2D/2DArray/3D";
  153. case hlsl::ValidationRule::InstrResourceKindForGetDim: return "Invalid resource kind on GetDimensions";
  154. case hlsl::ValidationRule::InstrResourceKindForTextureLoad: return "texture load only works on Texture1D/1DArray/2D/2DArray/3D/MS2D/MS2DArray";
  155. case hlsl::ValidationRule::InstrResourceClassForSamplerGather: return "sample, lod and gather should on srv resource.";
  156. case hlsl::ValidationRule::InstrResourceClassForUAVStore: return "store should on uav resource.";
  157. case hlsl::ValidationRule::InstrResourceClassForLoad: return "load can only run on UAV/SRV resource";
  158. case hlsl::ValidationRule::InstrOffsetOnUAVLoad: return "uav load don't support offset";
  159. case hlsl::ValidationRule::InstrMipOnUAVLoad: return "uav load don't support mipLevel/sampleIndex";
  160. case hlsl::ValidationRule::InstrSampleIndexForLoad2DMS: return "load on Texture2DMS/2DMSArray require sampleIndex";
  161. case hlsl::ValidationRule::InstrCoordinateCountForRawTypedBuf: return "raw/typed buffer don't need 2 coordinates";
  162. case hlsl::ValidationRule::InstrCoordinateCountForStructBuf: return "structured buffer require 2 coordinates";
  163. case hlsl::ValidationRule::InstrMipLevelForGetDimension: return "Use mip level on buffer when GetDimensions";
  164. case hlsl::ValidationRule::InstrDxilStructUser: return "Dxil struct types should only used by ExtractValue";
  165. case hlsl::ValidationRule::InstrDxilStructUserOutOfBound: return "Index out of bound when extract value from dxil struct types";
  166. case hlsl::ValidationRule::InstrHandleNotFromCreateHandle: return "Resource handle should returned by createHandle";
  167. case hlsl::ValidationRule::InstrBufferUpdateCounterOnUAV: return "BufferUpdateCounter valid only on UAV";
  168. case hlsl::ValidationRule::InstrCBufferOutOfBound: return "Cbuffer access out of bound";
  169. case hlsl::ValidationRule::InstrCBufferClassForCBufferHandle: return "Expect Cbuffer for CBufferLoad handle";
  170. case hlsl::ValidationRule::InstrFailToResloveTGSMPointer: return "TGSM pointers must originate from an unambiguous TGSM global variable.";
  171. case hlsl::ValidationRule::InstrExtractValue: return "ExtractValue should only be used on dxil struct types and cmpxchg";
  172. case hlsl::ValidationRule::InstrTGSMRaceCond: return "Race condition writing to shared memory detected, consider making this write conditional";
  173. case hlsl::ValidationRule::InstrAttributeAtVertexNoInterpolation: return "Attribute %0 must have nointerpolation mode in order to use GetAttributeAtVertex function.";
  174. case hlsl::ValidationRule::TypesNoVector: return "Vector type '%0' is not allowed";
  175. case hlsl::ValidationRule::TypesDefined: return "Type '%0' is not defined on DXIL primitives";
  176. case hlsl::ValidationRule::TypesIntWidth: return "Int type '%0' has an invalid width";
  177. case hlsl::ValidationRule::TypesNoMultiDim: return "Only one dimension allowed for array type";
  178. case hlsl::ValidationRule::TypesI8: return "I8 can only used as immediate value for intrinsic";
  179. case hlsl::ValidationRule::SmName: return "Unknown shader model '%0'";
  180. case hlsl::ValidationRule::SmDxilVersion: return "Shader model requires Dxil Version %0,%1";
  181. case hlsl::ValidationRule::SmOpcode: return "Opcode %0 not valid in shader model %1";
  182. case hlsl::ValidationRule::SmOperand: return "Operand must be defined in target shader model";
  183. case hlsl::ValidationRule::SmSemantic: return "Semantic '%0' is invalid as %1 %2";
  184. case hlsl::ValidationRule::SmNoInterpMode: return "Interpolation mode for '%0' is set but should be undefined";
  185. case hlsl::ValidationRule::SmNoPSOutputIdx: return "Pixel shader output registers are not indexable.";
  186. 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)";
  187. case hlsl::ValidationRule::SmThreadGroupChannelRange: return "Declared Thread Group %0 size %1 outside valid range [%2..%3]";
  188. case hlsl::ValidationRule::SmMaxTheadGroup: return "Declared Thread Group Count %0 (X*Y*Z) is beyond the valid maximum of %1";
  189. case hlsl::ValidationRule::SmMaxTGSMSize: return "Total Thread Group Shared Memory storage is %0, exceeded %1";
  190. case hlsl::ValidationRule::SmROVOnlyInPS: return "RasterizerOrdered objects are only allowed in 5.0+ pixel shaders";
  191. case hlsl::ValidationRule::SmTessFactorForDomain: return "Required TessFactor for domain not found declared anywhere in Patch Constant data";
  192. case hlsl::ValidationRule::SmTessFactorSizeMatchDomain: return "TessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  193. case hlsl::ValidationRule::SmInsideTessFactorSizeMatchDomain: return "InsideTessFactor rows, columns (%0, %1) invalid for domain %2. Expected %3 rows and 1 column.";
  194. case hlsl::ValidationRule::SmDomainLocationIdxOOB: return "DomainLocation component index out of bounds for the domain.";
  195. case hlsl::ValidationRule::SmHullPassThruControlPointCountMatch: return "For pass thru hull shader, input control point count must match output control point count";
  196. case hlsl::ValidationRule::SmOutputControlPointsTotalScalars: return "Total number of scalars across all HS output control points must not exceed ";
  197. 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.";
  198. 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";
  199. case hlsl::ValidationRule::SmValidDomain: return "Invalid Tessellator Domain specified. Must be isoline, tri or quad";
  200. case hlsl::ValidationRule::SmPatchConstantOnlyForHSDS: return "patch constant signature only valid in HS and DS";
  201. case hlsl::ValidationRule::SmStreamIndexRange: return "Stream index (%0) must between 0 and %1";
  202. 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";
  203. case hlsl::ValidationRule::SmPSMultipleDepthSemantic: return "Pixel Shader only allows one type of depth semantic to be declared";
  204. case hlsl::ValidationRule::SmPSTargetIndexMatchesRow: return "SV_Target semantic index must match packed row location";
  205. case hlsl::ValidationRule::SmPSTargetCol0: return "SV_Target packed location must start at column 0";
  206. case hlsl::ValidationRule::SmPSCoverageAndInnerCoverage: return "InnerCoverage and Coverage are mutually exclusive.";
  207. case hlsl::ValidationRule::SmGSOutputVertexCountRange: return "GS output vertex count must be [0..%0]. %1 specified";
  208. case hlsl::ValidationRule::SmGSInstanceCountRange: return "GS instance count must be [1..%0]. %1 specified";
  209. case hlsl::ValidationRule::SmDSInputControlPointCountRange: return "DS input control point count must be [0..%0]. %1 specified";
  210. case hlsl::ValidationRule::SmHSInputControlPointCountRange: return "HS input control point count must be [0..%0]. %1 specified";
  211. case hlsl::ValidationRule::SmZeroHSInputControlPointWithInput: return "When HS input control point count is 0, no input signature should exist";
  212. case hlsl::ValidationRule::SmOutputControlPointCountRange: return "output control point count must be [0..%0]. %1 specified";
  213. case hlsl::ValidationRule::SmGSValidInputPrimitive: return "GS input primitive unrecognized";
  214. case hlsl::ValidationRule::SmGSValidOutputPrimitiveTopology: return "GS output primitive topology unrecognized";
  215. 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.";
  216. case hlsl::ValidationRule::SmInvalidTextureKindOnUAV: return "Texture2DMS[Array] or TextureCube[Array] resources are not supported with UAVs";
  217. case hlsl::ValidationRule::SmInvalidResourceKind: return "Invalid resources kind";
  218. case hlsl::ValidationRule::SmInvalidResourceCompType: return "Invalid resource return type";
  219. case hlsl::ValidationRule::SmSampleCountOnlyOn2DMS: return "Only Texture2DMS/2DMSArray could has sample count";
  220. case hlsl::ValidationRule::SmCounterOnlyOnStructBuf: return "BufferUpdateCounter valid only on structured buffers";
  221. 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";
  222. case hlsl::ValidationRule::SmMultiStreamMustBePoint: return "Multiple GS output streams are used but '%0' is not pointlist";
  223. case hlsl::ValidationRule::SmCompletePosition: return "Not all elements of SV_Position were written";
  224. case hlsl::ValidationRule::SmUndefinedOutput: return "Not all elements of output %0 were written";
  225. case hlsl::ValidationRule::SmCSNoReturn: return "Compute shaders can't return values, outputs must be written in writable resources (UAVs).";
  226. case hlsl::ValidationRule::SmCBufferTemplateTypeMustBeStruct: return "D3D12 constant/texture buffer template element can only be a struct";
  227. case hlsl::ValidationRule::SmResourceRangeOverlap: return "Resource %0 with base %1 size %2 overlap with other resource with base %3 size %4 in space %5";
  228. case hlsl::ValidationRule::SmCBufferOffsetOverlap: return "CBuffer %0 has offset overlaps at %1";
  229. case hlsl::ValidationRule::SmCBufferElementOverflow: return "CBuffer %0 size insufficient for element at offset %1";
  230. case hlsl::ValidationRule::SmOpcodeInInvalidFunction: return "opcode '%0' should only used in '%1'";
  231. case hlsl::ValidationRule::SmViewIDNeedsSlot: return "Pixel shader input signature lacks available space for ViewID";
  232. case hlsl::ValidationRule::UniNoWaveSensitiveGradient: return "Gradient operations are not affected by wave-sensitive data or control flow.";
  233. case hlsl::ValidationRule::FlowReducible: return "Execution flow must be reducible";
  234. case hlsl::ValidationRule::FlowNoRecusion: return "Recursion is not permitted";
  235. case hlsl::ValidationRule::FlowDeadLoop: return "Loop must have break";
  236. case hlsl::ValidationRule::FlowFunctionCall: return "Function %0 with parameter is not permitted, it should be inlined";
  237. case hlsl::ValidationRule::DeclDxilNsReserved: return "Declaration '%0' uses a reserved prefix";
  238. case hlsl::ValidationRule::DeclDxilFnExtern: return "External function '%0' is not a DXIL function";
  239. case hlsl::ValidationRule::DeclUsedInternal: return "Internal declaration '%0' is unused";
  240. case hlsl::ValidationRule::DeclNotUsedExternal: return "External declaration '%0' is unused";
  241. case hlsl::ValidationRule::DeclUsedExternalFunction: return "External function '%0' is unused";
  242. case hlsl::ValidationRule::DeclFnIsCalled: return "Function '%0' is used for something other than calling";
  243. case hlsl::ValidationRule::DeclFnFlattenParam: return "Type '%0' is a struct type but is used as a parameter in function '%1'";
  244. case hlsl::ValidationRule::DeclFnAttribute: return "Function '%0' contains invalid attribute '%1' with value '%2'";
  245. }
  246. // VALRULE-TEXT:END
  247. llvm_unreachable("invalid value");
  248. return "<unknown>";
  249. }
  250. namespace {
  251. // Utility class for setting and restoring the diagnostic context so we may capture errors/warnings
  252. struct DiagRestore {
  253. LLVMContext &Ctx;
  254. void *OrigDiagContext;
  255. LLVMContext::DiagnosticHandlerTy OrigHandler;
  256. DiagRestore(llvm::LLVMContext &Ctx, void *DiagContext) : Ctx(Ctx) {
  257. OrigHandler = Ctx.getDiagnosticHandler();
  258. OrigDiagContext = Ctx.getDiagnosticContext();
  259. Ctx.setDiagnosticHandler(
  260. hlsl::PrintDiagnosticContext::PrintDiagnosticHandler, DiagContext);
  261. }
  262. ~DiagRestore() {
  263. Ctx.setDiagnosticHandler(OrigHandler, OrigDiagContext);
  264. }
  265. };
  266. class DxilErrorDiagnosticInfo : public DiagnosticInfo {
  267. private:
  268. const char *m_message;
  269. public:
  270. DxilErrorDiagnosticInfo(const char *str)
  271. : DiagnosticInfo(DK_FirstPluginKind, DiagnosticSeverity::DS_Error),
  272. m_message(str) { }
  273. __override void print(DiagnosticPrinter &DP) const {
  274. DP << m_message;
  275. }
  276. };
  277. static void emitDxilDiag(const LLVMContext &Ctx, const char *str) {
  278. // diagnose doesn't actually mutate anything.
  279. LLVMContext &diagCtx = const_cast<LLVMContext &>(Ctx);
  280. diagCtx.diagnose(DxilErrorDiagnosticInfo(str));
  281. }
  282. // Printing of types.
  283. static inline DiagnosticPrinter &operator<<(DiagnosticPrinter &OS, Type &T) {
  284. std::string O;
  285. raw_string_ostream OSS(O);
  286. T.print(OSS);
  287. OS << OSS.str();
  288. return OS;
  289. }
  290. } // anon namespace
  291. namespace hlsl {
  292. // PrintDiagnosticContext methods.
  293. PrintDiagnosticContext::PrintDiagnosticContext(DiagnosticPrinter &printer)
  294. : m_Printer(printer), m_errorsFound(false), m_warningsFound(false) {}
  295. bool PrintDiagnosticContext::HasErrors() const { return m_errorsFound; }
  296. bool PrintDiagnosticContext::HasWarnings() const { return m_warningsFound; }
  297. void PrintDiagnosticContext::Handle(const DiagnosticInfo &DI) {
  298. DI.print(m_Printer);
  299. switch (DI.getSeverity()) {
  300. case llvm::DiagnosticSeverity::DS_Error:
  301. m_errorsFound = true;
  302. break;
  303. case llvm::DiagnosticSeverity::DS_Warning:
  304. m_warningsFound = true;
  305. break;
  306. default:
  307. break;
  308. }
  309. m_Printer << "\n";
  310. }
  311. void PrintDiagnosticContext::PrintDiagnosticHandler(const DiagnosticInfo &DI, void *Context) {
  312. reinterpret_cast<hlsl::PrintDiagnosticContext *>(Context)->Handle(DI);
  313. }
  314. struct PSExecutionInfo {
  315. bool SuperSampling = false;
  316. DXIL::SemanticKind OutputDepthKind = DXIL::SemanticKind::Invalid;
  317. const InterpolationMode *PositionInterpolationMode = nullptr;
  318. };
  319. struct ValidationContext {
  320. bool Failed = false;
  321. Module &M;
  322. Module *pDebugModule;
  323. DxilModule &DxilMod;
  324. const DataLayout &DL;
  325. DiagnosticPrinterRawOStream &DiagPrinter;
  326. PSExecutionInfo PSExec;
  327. DebugLoc LastDebugLocEmit;
  328. ValidationRule LastRuleEmit;
  329. std::unordered_set<Function *> entryFuncCallSet;
  330. std::unordered_set<Function *> patchConstFuncCallSet;
  331. std::unordered_map<unsigned, bool> UavCounterIncMap;
  332. bool hasOutputPosition[DXIL::kNumOutputStreams];
  333. bool hasViewID;
  334. unsigned OutputPositionMask[DXIL::kNumOutputStreams];
  335. std::vector<unsigned> outputCols;
  336. std::vector<unsigned> patchConstCols;
  337. unsigned domainLocSize;
  338. const unsigned kDxilControlFlowHintMDKind;
  339. const unsigned kDxilPreciseMDKind;
  340. const unsigned kLLVMLoopMDKind;
  341. bool m_bCoverageIn, m_bInnerCoverageIn;
  342. unsigned m_DxilMajor, m_DxilMinor;
  343. ValidationContext(Module &llvmModule, Module *DebugModule,
  344. DxilModule &dxilModule,
  345. DiagnosticPrinterRawOStream &DiagPrn)
  346. : M(llvmModule), pDebugModule(DebugModule), DxilMod(dxilModule),
  347. DL(llvmModule.getDataLayout()),
  348. kDxilControlFlowHintMDKind(llvmModule.getContext().getMDKindID(
  349. DxilMDHelper::kDxilControlFlowHintMDName)),
  350. kDxilPreciseMDKind(llvmModule.getContext().getMDKindID(
  351. DxilMDHelper::kDxilPreciseAttributeMDName)),
  352. kLLVMLoopMDKind(llvmModule.getContext().getMDKindID("llvm.loop")),
  353. DiagPrinter(DiagPrn), LastRuleEmit((ValidationRule)-1),
  354. m_bCoverageIn(false), m_bInnerCoverageIn(false),
  355. hasViewID(false) {
  356. DxilMod.GetDxilVersion(m_DxilMajor, m_DxilMinor);
  357. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  358. hasOutputPosition[i] = false;
  359. OutputPositionMask[i] = 0;
  360. }
  361. outputCols.resize(DxilMod.GetOutputSignature().GetElements().size(), 0);
  362. patchConstCols.resize(DxilMod.GetPatchConstantSignature().GetElements().size(), 0);
  363. }
  364. // Provide direct access to the raw_ostream in DiagPrinter.
  365. raw_ostream &DiagStream() {
  366. struct DiagnosticPrinterRawOStream_Pub : public DiagnosticPrinterRawOStream {
  367. public:
  368. raw_ostream &DiagStream() { return Stream; }
  369. };
  370. DiagnosticPrinterRawOStream_Pub* p = (DiagnosticPrinterRawOStream_Pub*)&DiagPrinter;
  371. return p->DiagStream();
  372. }
  373. void EmitGlobalValueError(GlobalValue *GV, ValidationRule rule) {
  374. EmitFormatError(rule, { GV->getName().str() });
  375. }
  376. // This is the least desirable mechanism, as it has no context.
  377. void EmitError(ValidationRule rule) {
  378. DiagPrinter << GetValidationRuleText(rule) << '\n';
  379. Failed = true;
  380. }
  381. void FormatRuleText(std::string &ruleText, ArrayRef<StringRef> args) {
  382. // Consider changing const char * to StringRef
  383. for (unsigned i = 0; i < args.size(); i++) {
  384. std::string argIdx = "%" + std::to_string(i);
  385. StringRef pArg = args[i];
  386. if (pArg == "")
  387. pArg = "<null>";
  388. std::string::size_type offset = ruleText.find(argIdx);
  389. if (offset == std::string::npos)
  390. continue;
  391. unsigned size = argIdx.size();
  392. ruleText.replace(offset, size, args[i]);
  393. }
  394. }
  395. void EmitFormatError(ValidationRule rule, ArrayRef<StringRef> args) {
  396. std::string ruleText = GetValidationRuleText(rule);
  397. FormatRuleText(ruleText, args);
  398. DiagPrinter << ruleText << '\n';
  399. Failed = true;
  400. }
  401. void EmitMetaError(Metadata *Meta, ValidationRule rule) {
  402. DiagPrinter << GetValidationRuleText(rule);
  403. Meta->print(DiagStream(), &M);
  404. DiagPrinter << '\n';
  405. Failed = true;
  406. }
  407. void EmitResourceError(const hlsl::DxilResourceBase *Res, ValidationRule rule) {
  408. DiagPrinter << GetValidationRuleText(rule);
  409. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  410. DiagPrinter << '\n';
  411. Failed = true;
  412. }
  413. void EmitResourceFormatError(const hlsl::DxilResourceBase *Res,
  414. ValidationRule rule,
  415. ArrayRef<StringRef> args) {
  416. std::string ruleText = GetValidationRuleText(rule);
  417. FormatRuleText(ruleText, args);
  418. DiagPrinter << ruleText;
  419. DiagPrinter << '\'' << Res->GetGlobalName() << '\'';
  420. DiagPrinter << '\n';
  421. Failed = true;
  422. }
  423. bool IsDebugFunctionCall(Instruction *I) {
  424. CallInst *CI = dyn_cast<CallInst>(I);
  425. return CI && CI->getCalledFunction()->getName().startswith("llvm.dbg.");
  426. }
  427. DebugLoc GetDebugLoc(Instruction *I) {
  428. DXASSERT_NOMSG(I);
  429. if (pDebugModule) {
  430. // Look up the matching instruction in the debug module.
  431. llvm::Function *Fn = I->getParent()->getParent();
  432. llvm::Function *DbgFn = pDebugModule->getFunction(Fn->getName());
  433. if (DbgFn) {
  434. // Linear lookup, but then again, failing validation is rare.
  435. inst_iterator it = inst_begin(Fn);
  436. inst_iterator dbg_it = inst_begin(DbgFn);
  437. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  438. while (&*it != I) {
  439. ++it;
  440. ++dbg_it;
  441. while (IsDebugFunctionCall(&*dbg_it)) ++dbg_it;
  442. }
  443. return dbg_it->getDebugLoc();
  444. }
  445. }
  446. return I->getDebugLoc();
  447. }
  448. bool EmitInstrLoc(Instruction *I, ValidationRule Rule) {
  449. const DebugLoc &L = GetDebugLoc(I);
  450. if (L) {
  451. // Instructions that get scalarized will likely hit
  452. // this case. Avoid redundant diagnostic messages.
  453. if (Rule == LastRuleEmit && L == LastDebugLocEmit) {
  454. return false;
  455. }
  456. LastRuleEmit = Rule;
  457. LastDebugLocEmit = L;
  458. L.print(DiagStream());
  459. DiagPrinter << ' ';
  460. return true;
  461. }
  462. BasicBlock *BB = I->getParent();
  463. Function *F = BB->getParent();
  464. DiagPrinter << "at " << I;
  465. DiagPrinter << " inside block ";
  466. if (!BB->getName().empty()) {
  467. DiagPrinter << BB->getName();
  468. }
  469. else {
  470. unsigned idx = 0;
  471. for (auto i = F->getBasicBlockList().begin(),
  472. e = F->getBasicBlockList().end(); i != e; ++i) {
  473. if (BB == &(*i)) {
  474. break;
  475. }
  476. }
  477. DiagPrinter << "#" << idx;
  478. }
  479. DiagPrinter << " of function " << *F << ' ';
  480. return true;
  481. }
  482. void EmitInstrError(Instruction *I, ValidationRule rule) {
  483. if (!EmitInstrLoc(I, rule)) return;
  484. DiagPrinter << GetValidationRuleText(rule);
  485. DiagPrinter << '\n';
  486. Failed = true;
  487. }
  488. void EmitInstrFormatError(Instruction *I, ValidationRule rule, ArrayRef<StringRef> args) {
  489. if (!EmitInstrLoc(I, rule)) return;
  490. std::string ruleText = GetValidationRuleText(rule);
  491. FormatRuleText(ruleText, args);
  492. DiagPrinter << ruleText;
  493. DiagPrinter << '\n';
  494. Failed = true;
  495. }
  496. void EmitOperandOutOfRange(Instruction *I, StringRef name, StringRef range, StringRef v) {
  497. if (!EmitInstrLoc(I, ValidationRule::InstrOperandRange)) return;
  498. std::string ruleText = GetValidationRuleText(ValidationRule::InstrOperandRange);
  499. FormatRuleText(ruleText, {name, range, v});
  500. DiagPrinter << ruleText;
  501. DiagPrinter << '\n';
  502. Failed = true;
  503. }
  504. void EmitSignatureError(DxilSignatureElement *SE, ValidationRule rule) {
  505. EmitFormatError(rule, { SE->GetName() });
  506. }
  507. void EmitTypeError(Type *Ty, ValidationRule rule) {
  508. std::string O;
  509. raw_string_ostream OSS(O);
  510. Ty->print(OSS);
  511. EmitFormatError(rule, { OSS.str() });
  512. }
  513. void EmitFnAttributeError(Function *F, StringRef Kind, StringRef Value) {
  514. EmitFormatError(ValidationRule::DeclFnAttribute, { F->getName(), Kind, Value });
  515. }
  516. };
  517. static bool ValidateOpcodeInProfile(DXIL::OpCode opcode,
  518. const ShaderModel *pSM) {
  519. unsigned op = (unsigned)opcode;
  520. /* <py::lines('VALOPCODESM-TEXT')>hctdb_instrhelp.get_valopcode_sm_text()</py>*/
  521. // VALOPCODESM-TEXT:BEGIN
  522. // Instructions: ThreadId=93, GroupId=94, ThreadIdInGroup=95,
  523. // FlattenedThreadIdInGroup=96
  524. if (93 <= op && op <= 96)
  525. return (pSM->IsCS());
  526. // Instructions: DomainLocation=105
  527. if (op == 105)
  528. return (pSM->IsDS());
  529. // Instructions: LoadOutputControlPoint=103, LoadPatchConstant=104
  530. if (103 <= op && op <= 104)
  531. return (pSM->IsDS() || pSM->IsHS());
  532. // Instructions: EmitStream=97, CutStream=98, EmitThenCutStream=99,
  533. // GSInstanceID=100
  534. if (97 <= op && op <= 100)
  535. return (pSM->IsGS());
  536. // Instructions: PrimitiveID=108
  537. if (op == 108)
  538. return (pSM->IsGS() || pSM->IsDS() || pSM->IsHS() || pSM->IsPS());
  539. // Instructions: StorePatchConstant=106, OutputControlPointID=107
  540. if (106 <= op && op <= 107)
  541. return (pSM->IsHS());
  542. // Instructions: Sample=60, SampleBias=61, SampleCmp=64,
  543. // RenderTargetGetSamplePosition=76, RenderTargetGetSampleCount=77,
  544. // CalculateLOD=81, Discard=82, DerivCoarseX=83, DerivCoarseY=84,
  545. // DerivFineX=85, DerivFineY=86, EvalSnapped=87, EvalSampleIndex=88,
  546. // EvalCentroid=89, SampleIndex=90, Coverage=91, InnerCoverage=92
  547. if (60 <= op && op <= 61 || op == 64 || 76 <= op && op <= 77 || 81 <= op && op <= 92)
  548. return (pSM->IsPS());
  549. // Instructions: AttributeAtVertex=137
  550. if (op == 137)
  551. return (pSM->GetMajor() > 6 || (pSM->GetMajor() == 6 && pSM->GetMinor() >= 1))
  552. && (pSM->IsPS());
  553. // Instructions: ViewID=138
  554. if (op == 138)
  555. return (pSM->GetMajor() > 6 || (pSM->GetMajor() == 6 && pSM->GetMinor() >= 1))
  556. && (pSM->IsVS() || pSM->IsHS() || pSM->IsDS() || pSM->IsGS() || pSM->IsPS());
  557. // Instructions: RawBufferLoad=139, RawBufferStore=140
  558. if (139 <= op && op <= 140)
  559. return (pSM->GetMajor() > 6 || (pSM->GetMajor() == 6 && pSM->GetMinor() >= 2));
  560. return true;
  561. // VALOPCODESM-TEXT:END
  562. }
  563. static unsigned ValidateSignatureRowCol(Instruction *I, DxilSignatureElement &SE,
  564. Value *rowVal, Value *colVal,
  565. ValidationContext &ValCtx) {
  566. if (ConstantInt *constRow = dyn_cast<ConstantInt>(rowVal)) {
  567. unsigned row = constRow->getLimitedValue();
  568. if (row >= SE.GetRows()) {
  569. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  570. }
  571. }
  572. if (!isa<ConstantInt>(colVal)) {
  573. // col must be const
  574. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  575. {"Col", "LoadInput/StoreOutput"});
  576. return 0;
  577. }
  578. unsigned col = cast<ConstantInt>(colVal)->getLimitedValue();
  579. if (col > SE.GetCols()) {
  580. ValCtx.EmitInstrError(I, ValidationRule::InstrOperandRange);
  581. } else {
  582. if (SE.IsOutput())
  583. ValCtx.outputCols[SE.GetID()] |= 1 << col;
  584. if (SE.IsPatchConstant())
  585. ValCtx.patchConstCols[SE.GetID()] |= 1 << col;
  586. }
  587. return col;
  588. }
  589. static DxilSignatureElement *ValidateSignatureAccess(Instruction *I, DxilSignature &sig,
  590. Value *sigID, Value *rowVal, Value *colVal,
  591. ValidationContext &ValCtx) {
  592. if (!isa<ConstantInt>(sigID)) {
  593. // inputID must be const
  594. ValCtx.EmitInstrFormatError(I, ValidationRule::InstrOpConst,
  595. {"SignatureID", "LoadInput/StoreOutput"});
  596. return nullptr;
  597. }
  598. unsigned SEIdx = cast<ConstantInt>(sigID)->getLimitedValue();
  599. if (sig.GetElements().size() <= SEIdx) {
  600. ValCtx.EmitInstrError(I, ValidationRule::InstrOpConstRange);
  601. return nullptr;
  602. }
  603. DxilSignatureElement &SE = sig.GetElement(SEIdx);
  604. bool isOutput = sig.IsOutput();
  605. unsigned col = ValidateSignatureRowCol(I, SE, rowVal, colVal, ValCtx);
  606. if (isOutput && SE.GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  607. unsigned mask = ValCtx.OutputPositionMask[SE.GetOutputStream()];
  608. mask |= 1<<col;
  609. if (SE.GetOutputStream() < DXIL::kNumOutputStreams)
  610. ValCtx.OutputPositionMask[SE.GetOutputStream()] = mask;
  611. }
  612. return &SE;
  613. }
  614. static DXIL::SamplerKind GetSamplerKind(Value *samplerHandle, ValidationContext &ValCtx) {
  615. if (!isa<CallInst>(samplerHandle)) {
  616. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  617. return DXIL::SamplerKind::Invalid;
  618. }
  619. DxilInst_CreateHandle createHandle(cast<CallInst>(samplerHandle));
  620. if (!createHandle) {
  621. ValCtx.EmitInstrError(cast<CallInst>(samplerHandle), ValidationRule::InstrHandleNotFromCreateHandle);
  622. return DXIL::SamplerKind::Invalid;
  623. }
  624. Value *resClass = createHandle.get_resourceClass();
  625. if (!isa<ConstantInt>(resClass)) {
  626. return DXIL::SamplerKind::Invalid;
  627. }
  628. if (createHandle.get_resourceClass_val() != static_cast<unsigned>(DXIL::ResourceClass::Sampler)) {
  629. // must be sampler.
  630. return DXIL::SamplerKind::Invalid;
  631. }
  632. Value *rangeIndex = createHandle.get_rangeId();
  633. if (!isa<ConstantInt>(rangeIndex)) {
  634. // must be constant
  635. return DXIL::SamplerKind::Invalid;
  636. }
  637. unsigned samplerIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  638. auto &samplers = ValCtx.DxilMod.GetSamplers();
  639. if (samplerIndex >= samplers.size()) {
  640. return DXIL::SamplerKind::Invalid;
  641. }
  642. DxilSampler *sampler = samplers[samplerIndex].get();
  643. Value *index = createHandle.get_index();
  644. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  645. if (!sampler->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  646. if (!cIndex) {
  647. // index must be 0 for none array resource.
  648. return DXIL::SamplerKind::Invalid;
  649. }
  650. }
  651. if (cIndex) {
  652. unsigned index = cIndex->getLimitedValue();
  653. if (index < sampler->GetLowerBound() || index > sampler->GetUpperBound()) {
  654. // index out of range.
  655. return DXIL::SamplerKind::Invalid;
  656. }
  657. }
  658. return sampler->GetSamplerKind();
  659. }
  660. static DXIL::ResourceKind GetResourceKindAndCompTy(Value *handle, DXIL::ComponentType &CompTy, DXIL::ResourceClass &ResClass,
  661. unsigned &resIndex,
  662. ValidationContext &ValCtx) {
  663. CompTy = DXIL::ComponentType::Invalid;
  664. ResClass = DXIL::ResourceClass::Invalid;
  665. if (!isa<CallInst>(handle)) {
  666. ValCtx.EmitError(ValidationRule::InstrHandleNotFromCreateHandle);
  667. return DXIL::ResourceKind::Invalid;
  668. }
  669. DxilInst_CreateHandle createHandle(cast<CallInst>(handle));
  670. if (!createHandle) {
  671. ValCtx.EmitInstrError(cast<CallInst>(handle), ValidationRule::InstrHandleNotFromCreateHandle);
  672. return DXIL::ResourceKind::Invalid;
  673. }
  674. Value *resourceClass = createHandle.get_resourceClass();
  675. if (!isa<ConstantInt>(resourceClass)) {
  676. return DXIL::ResourceKind::Invalid;
  677. }
  678. ResClass = static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val());
  679. switch (ResClass) {
  680. case DXIL::ResourceClass::SRV:
  681. case DXIL::ResourceClass::UAV:
  682. break;
  683. case DXIL::ResourceClass::CBuffer:
  684. return DXIL::ResourceKind::CBuffer;
  685. case DXIL::ResourceClass::Sampler:
  686. return DXIL::ResourceKind::Sampler;
  687. default:
  688. // Emit invalid res class
  689. return DXIL::ResourceKind::Invalid;
  690. }
  691. Value *rangeIndex = createHandle.get_rangeId();
  692. if (!isa<ConstantInt>(rangeIndex)) {
  693. // must be constant
  694. return DXIL::ResourceKind::Invalid;
  695. }
  696. resIndex = cast<ConstantInt>(rangeIndex)->getLimitedValue();
  697. DxilResource *res = nullptr;
  698. if (ResClass == DXIL::ResourceClass::UAV) {
  699. auto &resources = ValCtx.DxilMod.GetUAVs();
  700. if (resIndex >= resources.size()) {
  701. return DXIL::ResourceKind::Invalid;
  702. }
  703. res = resources[resIndex].get();
  704. } else {
  705. if (ResClass != DXIL::ResourceClass::SRV) {
  706. return DXIL::ResourceKind::Invalid;
  707. }
  708. auto &resources = ValCtx.DxilMod.GetSRVs();
  709. if (resIndex >= resources.size()) {
  710. return DXIL::ResourceKind::Invalid;
  711. }
  712. res = resources[resIndex].get();
  713. }
  714. CompTy = res->GetCompType().GetKind();
  715. Value *index = createHandle.get_index();
  716. ConstantInt *cIndex = dyn_cast<ConstantInt>(index);
  717. if (!res->GetGlobalSymbol()->getType()->getPointerElementType()->isArrayTy()) {
  718. if (!cIndex) {
  719. // index must be 0 for none array resource.
  720. return DXIL::ResourceKind::Invalid;
  721. }
  722. }
  723. if (cIndex) {
  724. unsigned index = cIndex->getLimitedValue();
  725. if (index < res->GetLowerBound() || index > res->GetUpperBound()) {
  726. // index out of range.
  727. return DXIL::ResourceKind::Invalid;
  728. }
  729. }
  730. return res->GetKind();
  731. }
  732. struct ResRetUsage {
  733. bool x;
  734. bool y;
  735. bool z;
  736. bool w;
  737. bool status;
  738. ResRetUsage() : x(false), y(false), z(false), w(false), status(false) {}
  739. };
  740. static void CollectGetDimResRetUsage(ResRetUsage &usage, Instruction *ResRet,
  741. ValidationContext &ValCtx) {
  742. const unsigned kMaxResRetElementIndex = 5;
  743. for (User *U : ResRet->users()) {
  744. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
  745. for (unsigned idx : EVI->getIndices()) {
  746. switch (idx) {
  747. case 0:
  748. usage.x = true;
  749. break;
  750. case 1:
  751. usage.y = true;
  752. break;
  753. case 2:
  754. usage.z = true;
  755. break;
  756. case 3:
  757. usage.w = true;
  758. break;
  759. case DXIL::kResRetStatusIndex:
  760. usage.status = true;
  761. break;
  762. default:
  763. // Emit index out of bound.
  764. ValCtx.EmitInstrError(EVI,
  765. ValidationRule::InstrDxilStructUserOutOfBound);
  766. break;
  767. }
  768. }
  769. } else if (PHINode *PHI = dyn_cast<PHINode>(U)) {
  770. CollectGetDimResRetUsage(usage, PHI, ValCtx);
  771. } else {
  772. Instruction *User = cast<Instruction>(U);
  773. ValCtx.EmitInstrError(User, ValidationRule::InstrDxilStructUser);
  774. }
  775. }
  776. }
  777. static void ValidateStatus(Instruction *ResRet, ValidationContext &ValCtx) {
  778. ResRetUsage usage;
  779. CollectGetDimResRetUsage(usage, ResRet, ValCtx);
  780. if (usage.status) {
  781. for (User *U : ResRet->users()) {
  782. if (ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(U)) {
  783. for (unsigned idx : EVI->getIndices()) {
  784. switch (idx) {
  785. case DXIL::kResRetStatusIndex:
  786. for (User *SU : EVI->users()) {
  787. Instruction *I = cast<Instruction>(SU);
  788. // Make sure all use is CheckAccess.
  789. if (!isa<CallInst>(I)) {
  790. ValCtx.EmitInstrError(I, ValidationRule::InstrStatus);
  791. return;
  792. }
  793. if (!ValCtx.DxilMod.GetOP()->IsDxilOpFuncCallInst(
  794. I, DXIL::OpCode::CheckAccessFullyMapped)) {
  795. ValCtx.EmitInstrError(I, ValidationRule::InstrStatus);
  796. return;
  797. }
  798. }
  799. break;
  800. }
  801. }
  802. }
  803. }
  804. }
  805. }
  806. static void ValidateResourceCoord(CallInst *CI, DXIL::ResourceKind resKind,
  807. ArrayRef<Value *> coords,
  808. ValidationContext &ValCtx) {
  809. const unsigned kMaxNumCoords = 4;
  810. unsigned numCoords = DxilResource::GetNumCoords(resKind);
  811. for (unsigned i = 0; i < kMaxNumCoords; i++) {
  812. if (i < numCoords) {
  813. if (isa<UndefValue>(coords[i])) {
  814. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  815. }
  816. } else {
  817. if (!isa<UndefValue>(coords[i])) {
  818. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  819. }
  820. }
  821. }
  822. }
  823. static void ValidateCalcLODResourceDimensionCoord(CallInst *CI, DXIL::ResourceKind resKind,
  824. ArrayRef<Value *> coords,
  825. ValidationContext &ValCtx) {
  826. const unsigned kMaxNumDimCoords = 3;
  827. unsigned numCoords = DxilResource::GetNumDimensionsForCalcLOD(resKind);
  828. for (unsigned i = 0; i < kMaxNumDimCoords; i++) {
  829. if (i < numCoords) {
  830. if (isa<UndefValue>(coords[i])) {
  831. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateMiss);
  832. }
  833. } else {
  834. if (!isa<UndefValue>(coords[i])) {
  835. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceCoordinateTooMany);
  836. }
  837. }
  838. }
  839. }
  840. static void ValidateResourceOffset(CallInst *CI, DXIL::ResourceKind resKind,
  841. ArrayRef<Value *> offsets,
  842. ValidationContext &ValCtx) {
  843. const unsigned kMaxNumOffsets = 3;
  844. unsigned numOffsets = DxilResource::GetNumOffsets(resKind);
  845. bool hasOffset = !isa<UndefValue>(offsets[0]);
  846. auto validateOffset = [&](Value *offset) {
  847. if (ConstantInt *cOffset = dyn_cast<ConstantInt>(offset)) {
  848. int offset = cOffset->getValue().getSExtValue();
  849. if (offset > 7 || offset < -8) {
  850. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  851. }
  852. } else {
  853. ValCtx.EmitInstrError(CI, ValidationRule::InstrTextureOffset);
  854. }
  855. };
  856. if (hasOffset) {
  857. validateOffset(offsets[0]);
  858. }
  859. for (unsigned i = 1; i < kMaxNumOffsets; i++) {
  860. if (i < numOffsets) {
  861. if (hasOffset) {
  862. if (isa<UndefValue>(offsets[i]))
  863. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  864. else
  865. validateOffset(offsets[i]);
  866. }
  867. } else {
  868. if (!isa<UndefValue>(offsets[i])) {
  869. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  870. }
  871. }
  872. }
  873. }
  874. static void ValidateSampleInst(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  875. ArrayRef<Value *> coords,
  876. ArrayRef<Value *> offsets,
  877. bool IsSampleC,
  878. ValidationContext &ValCtx) {
  879. if (!IsSampleC) {
  880. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  881. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  882. }
  883. } else {
  884. if (GetSamplerKind(samplerHandle, ValCtx) !=
  885. DXIL::SamplerKind::Comparison) {
  886. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  887. }
  888. }
  889. DXIL::ComponentType compTy;
  890. DXIL::ResourceClass resClass;
  891. unsigned resIndex;
  892. DXIL::ResourceKind resKind =
  893. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  894. bool isSampleCompTy = compTy == DXIL::ComponentType::F32;
  895. isSampleCompTy |= compTy == DXIL::ComponentType::SNormF32;
  896. isSampleCompTy |= compTy == DXIL::ComponentType::UNormF32;
  897. if (!isSampleCompTy) {
  898. ValCtx.EmitInstrError(CI, ValidationRule::InstrSampleCompType);
  899. }
  900. if (resClass != DXIL::ResourceClass::SRV) {
  901. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  902. }
  903. ValidationRule rule = ValidationRule::InstrResourceKindForSample;
  904. if (IsSampleC) {
  905. rule = ValidationRule::InstrResourceKindForSampleC;
  906. }
  907. switch (resKind) {
  908. case DXIL::ResourceKind::Texture1D:
  909. case DXIL::ResourceKind::Texture1DArray:
  910. case DXIL::ResourceKind::Texture2D:
  911. case DXIL::ResourceKind::Texture2DArray:
  912. case DXIL::ResourceKind::TextureCube:
  913. case DXIL::ResourceKind::TextureCubeArray:
  914. break;
  915. case DXIL::ResourceKind::Texture3D:
  916. if (IsSampleC) {
  917. ValCtx.EmitInstrError(CI, rule);
  918. }
  919. break;
  920. default:
  921. ValCtx.EmitInstrError(CI, rule);
  922. return;
  923. }
  924. // Coord match resource kind.
  925. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  926. // Offset match resource kind.
  927. ValidateResourceOffset(CI, resKind, offsets, ValCtx);
  928. }
  929. static void ValidateGather(CallInst *CI, Value *srvHandle, Value *samplerHandle,
  930. ArrayRef<Value *> coords,
  931. ArrayRef<Value *> offsets,
  932. bool IsSampleC,
  933. ValidationContext &ValCtx) {
  934. if (!IsSampleC) {
  935. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  936. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSample);
  937. }
  938. } else {
  939. if (GetSamplerKind(samplerHandle, ValCtx) !=
  940. DXIL::SamplerKind::Comparison) {
  941. ValCtx.EmitInstrError(CI, ValidationRule::InstrSamplerModeForSampleC);
  942. }
  943. }
  944. DXIL::ComponentType compTy;
  945. DXIL::ResourceClass resClass;
  946. unsigned resIndex;
  947. DXIL::ResourceKind resKind =
  948. GetResourceKindAndCompTy(srvHandle, compTy, resClass, resIndex, ValCtx);
  949. if (resClass != DXIL::ResourceClass::SRV) {
  950. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForSamplerGather);
  951. return;
  952. }
  953. // Coord match resource kind.
  954. ValidateResourceCoord(CI, resKind, coords, ValCtx);
  955. // Offset match resource kind.
  956. switch (resKind) {
  957. case DXIL::ResourceKind::Texture2D:
  958. case DXIL::ResourceKind::Texture2DArray: {
  959. bool hasOffset = !isa<UndefValue>(offsets[0]);
  960. if (hasOffset) {
  961. if (isa<UndefValue>(offsets[1])) {
  962. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetMiss);
  963. }
  964. }
  965. } break;
  966. case DXIL::ResourceKind::TextureCube:
  967. case DXIL::ResourceKind::TextureCubeArray: {
  968. if (!isa<UndefValue>(offsets[0])) {
  969. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  970. }
  971. if (!isa<UndefValue>(offsets[1])) {
  972. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceOffsetTooMany);
  973. }
  974. } break;
  975. default:
  976. // Invalid resource type for gather.
  977. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceKindForGather);
  978. break;
  979. }
  980. }
  981. static unsigned StoreValueToMask(ArrayRef<Value *> vals) {
  982. unsigned mask = 0;
  983. for (unsigned i = 0; i < 4; i++) {
  984. if (!isa<UndefValue>(vals[i])) {
  985. mask |= 1<<i;
  986. }
  987. }
  988. return mask;
  989. }
  990. static int GetCBufSize(Value *cbHandle, ValidationContext &ValCtx) {
  991. DxilInst_CreateHandle createHandle(cast<CallInst>(cbHandle));
  992. if (!createHandle) {
  993. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  994. ValidationRule::InstrHandleNotFromCreateHandle);
  995. return -1;
  996. }
  997. Value *resourceClass = createHandle.get_resourceClass();
  998. if (!isa<ConstantInt>(resourceClass)) {
  999. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  1000. ValidationRule::InstrOpConstRange);
  1001. return -1;
  1002. }
  1003. if (static_cast<DXIL::ResourceClass>(createHandle.get_resourceClass_val()) !=
  1004. DXIL::ResourceClass::CBuffer) {
  1005. ValCtx.EmitInstrError(cast<CallInst>(cbHandle), ValidationRule::InstrCBufferClassForCBufferHandle);
  1006. return -1;
  1007. }
  1008. Value *rangeIndex = createHandle.get_rangeId();
  1009. if (!isa<ConstantInt>(rangeIndex)) {
  1010. ValCtx.EmitInstrError(cast<CallInst>(cbHandle),
  1011. ValidationRule::InstrOpConstRange);
  1012. return -1;
  1013. }
  1014. DxilCBuffer &CB = ValCtx.DxilMod.GetCBuffer(
  1015. cast<ConstantInt>(rangeIndex)->getLimitedValue());
  1016. return CB.GetSize();
  1017. }
  1018. static unsigned GetNumVertices(DXIL::InputPrimitive inputPrimitive) {
  1019. const unsigned InputPrimitiveVertexTab[] = {
  1020. 0, // Undefined = 0,
  1021. 1, // Point = 1,
  1022. 2, // Line = 2,
  1023. 3, // Triangle = 3,
  1024. 0, // Reserved4 = 4,
  1025. 0, // Reserved5 = 5,
  1026. 4, // LineWithAdjacency = 6,
  1027. 6, // TriangleWithAdjacency = 7,
  1028. 1, // ControlPointPatch1 = 8,
  1029. 2, // ControlPointPatch2 = 9,
  1030. 3, // ControlPointPatch3 = 10,
  1031. 4, // ControlPointPatch4 = 11,
  1032. 5, // ControlPointPatch5 = 12,
  1033. 6, // ControlPointPatch6 = 13,
  1034. 7, // ControlPointPatch7 = 14,
  1035. 8, // ControlPointPatch8 = 15,
  1036. 9, // ControlPointPatch9 = 16,
  1037. 10, // ControlPointPatch10 = 17,
  1038. 11, // ControlPointPatch11 = 18,
  1039. 12, // ControlPointPatch12 = 19,
  1040. 13, // ControlPointPatch13 = 20,
  1041. 14, // ControlPointPatch14 = 21,
  1042. 15, // ControlPointPatch15 = 22,
  1043. 16, // ControlPointPatch16 = 23,
  1044. 17, // ControlPointPatch17 = 24,
  1045. 18, // ControlPointPatch18 = 25,
  1046. 19, // ControlPointPatch19 = 26,
  1047. 20, // ControlPointPatch20 = 27,
  1048. 21, // ControlPointPatch21 = 28,
  1049. 22, // ControlPointPatch22 = 29,
  1050. 23, // ControlPointPatch23 = 30,
  1051. 24, // ControlPointPatch24 = 31,
  1052. 25, // ControlPointPatch25 = 32,
  1053. 26, // ControlPointPatch26 = 33,
  1054. 27, // ControlPointPatch27 = 34,
  1055. 28, // ControlPointPatch28 = 35,
  1056. 29, // ControlPointPatch29 = 36,
  1057. 30, // ControlPointPatch30 = 37,
  1058. 31, // ControlPointPatch31 = 38,
  1059. 32, // ControlPointPatch32 = 39,
  1060. 0, // LastEntry,
  1061. };
  1062. unsigned primitiveIdx = static_cast<unsigned>(inputPrimitive);
  1063. return InputPrimitiveVertexTab[primitiveIdx];
  1064. }
  1065. static void ValidateDxilOperationCallInProfile(CallInst *CI,
  1066. DXIL::OpCode opcode,
  1067. const ShaderModel *pSM,
  1068. ValidationContext &ValCtx) {
  1069. switch (opcode) {
  1070. case DXIL::OpCode::LoadInput: {
  1071. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1072. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1073. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1074. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1075. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  1076. // Check vertexID in ps/vs. and none array input.
  1077. Value *vertexID =
  1078. CI->getArgOperand(DXIL::OperandIndex::kLoadInputVertexIDOpIdx);
  1079. bool usedVertexID = vertexID && !isa<UndefValue>(vertexID);
  1080. if (pSM->IsVS() || pSM->IsPS()) {
  1081. if (usedVertexID) {
  1082. // use vertexID in VS/PS input.
  1083. ValCtx.EmitInstrError(CI, ValidationRule::SmOperand);
  1084. return;
  1085. }
  1086. } else {
  1087. if (ConstantInt *cVertexID = dyn_cast<ConstantInt>(vertexID)) {
  1088. int immVertexID = cVertexID->getValue().getLimitedValue();
  1089. if (cVertexID->getValue().isNegative()) {
  1090. immVertexID = cVertexID->getValue().getSExtValue();
  1091. }
  1092. const int low = 0;
  1093. int high = 0;
  1094. if (pSM->IsGS()) {
  1095. DXIL::InputPrimitive inputPrimitive =
  1096. ValCtx.DxilMod.GetInputPrimitive();
  1097. high = GetNumVertices(inputPrimitive);
  1098. } else if (pSM->IsDS()) {
  1099. high = ValCtx.DxilMod.GetInputControlPointCount();
  1100. } else if (pSM->IsHS()) {
  1101. high = ValCtx.DxilMod.GetInputControlPointCount();
  1102. } else {
  1103. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1104. {"LoadInput", "VS/HS/DS/GS/PS"});
  1105. }
  1106. if (immVertexID < low || immVertexID >= high) {
  1107. std::string range = std::to_string(low)+"~"+
  1108. std::to_string(high);
  1109. ValCtx.EmitOperandOutOfRange(CI, "VertexID", range,
  1110. std::to_string(immVertexID));
  1111. }
  1112. }
  1113. }
  1114. } break;
  1115. case DXIL::OpCode::DomainLocation: {
  1116. Value *colValue = CI->getArgOperand(DXIL::OperandIndex::kDomainLocationColOpIdx);
  1117. if (!isa<ConstantInt>(colValue)) {
  1118. // col must be const
  1119. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1120. {"Col", "DomainLocation"});
  1121. } else {
  1122. unsigned col = cast<ConstantInt>(colValue)->getLimitedValue();
  1123. if (col >= ValCtx.domainLocSize) {
  1124. ValCtx.EmitError(ValidationRule::SmDomainLocationIdxOOB);
  1125. }
  1126. }
  1127. } break;
  1128. case DXIL::OpCode::CBufferLoad: {
  1129. DxilInst_CBufferLoad CBLoad(CI);
  1130. Value *regIndex = CBLoad.get_byteOffset();
  1131. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1132. int offset = cIndex->getLimitedValue();
  1133. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1134. if (size > 0 && offset >= size) {
  1135. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1136. }
  1137. }
  1138. } break;
  1139. case DXIL::OpCode::CBufferLoadLegacy: {
  1140. DxilInst_CBufferLoadLegacy CBLoad(CI);
  1141. Value *regIndex = CBLoad.get_regIndex();
  1142. if (ConstantInt *cIndex = dyn_cast<ConstantInt>(regIndex)) {
  1143. int offset = cIndex->getLimitedValue() * 16; // 16 bytes align
  1144. int size = GetCBufSize(CBLoad.get_handle(), ValCtx);
  1145. if (size > 0 && offset >= size) {
  1146. ValCtx.EmitInstrError(CI, ValidationRule::InstrCBufferOutOfBound);
  1147. }
  1148. }
  1149. } break;
  1150. case DXIL::OpCode::StoreOutput: {
  1151. Value *outputID =
  1152. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1153. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1154. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1155. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1156. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1157. } break;
  1158. case DXIL::OpCode::OutputControlPointID: {
  1159. // Only used in hull shader.
  1160. Function *func = CI->getParent()->getParent();
  1161. if (ValCtx.patchConstFuncCallSet.count(func) > 0 || !ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  1162. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1163. {"OutputControlPointID", "hull function"});
  1164. }
  1165. } break;
  1166. case DXIL::OpCode::LoadOutputControlPoint: {
  1167. // Only used in patch constant function.
  1168. Function *func = CI->getParent()->getParent();
  1169. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1170. ValCtx.EmitFormatError(
  1171. ValidationRule::SmOpcodeInInvalidFunction,
  1172. {"LoadOutputControlPoint", "PatchConstant function"});
  1173. }
  1174. Value *outputID =
  1175. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1176. DxilSignature &outputSig = ValCtx.DxilMod.GetOutputSignature();
  1177. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1178. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1179. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1180. } break;
  1181. case DXIL::OpCode::StorePatchConstant: {
  1182. // Only used in patch constant function.
  1183. Function *func = CI->getParent()->getParent();
  1184. if (ValCtx.entryFuncCallSet.count(func) > 0) {
  1185. ValCtx.EmitFormatError(ValidationRule::SmOpcodeInInvalidFunction,
  1186. {"StorePatchConstant", "PatchConstant function"});
  1187. }
  1188. Value *outputID =
  1189. CI->getArgOperand(DXIL::OperandIndex::kStoreOutputIDOpIdx);
  1190. DxilSignature &outputSig = ValCtx.DxilMod.GetPatchConstantSignature();
  1191. Value *row = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputRowOpIdx);
  1192. Value *col = CI->getArgOperand(DXIL::OperandIndex::kStoreOutputColOpIdx);
  1193. ValidateSignatureAccess(CI, outputSig, outputID, row, col, ValCtx);
  1194. } break;
  1195. case DXIL::OpCode::EvalCentroid:
  1196. case DXIL::OpCode::EvalSampleIndex:
  1197. case DXIL::OpCode::EvalSnapped: {
  1198. // Eval* share same operand index with load input.
  1199. Value *inputID = CI->getArgOperand(DXIL::OperandIndex::kLoadInputIDOpIdx);
  1200. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1201. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1202. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1203. DxilSignatureElement *pSE =
  1204. ValidateSignatureAccess(CI, inputSig, inputID, row, col, ValCtx);
  1205. if (pSE) {
  1206. switch (pSE->GetInterpolationMode()->GetKind()) {
  1207. case DXIL::InterpolationMode::Linear:
  1208. case DXIL::InterpolationMode::LinearNoperspective:
  1209. case DXIL::InterpolationMode::LinearCentroid:
  1210. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  1211. case DXIL::InterpolationMode::LinearSample:
  1212. case DXIL::InterpolationMode::LinearNoperspectiveSample:
  1213. break;
  1214. default:
  1215. ValCtx.EmitInstrFormatError(
  1216. CI, ValidationRule::InstrEvalInterpolationMode, {pSE->GetName()});
  1217. break;
  1218. }
  1219. if (pSE->GetSemantic()->GetKind() == DXIL::SemanticKind::Position) {
  1220. ValCtx.EmitInstrFormatError(
  1221. CI, ValidationRule::InstrCannotPullPosition,
  1222. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  1223. }
  1224. }
  1225. } break;
  1226. case DXIL::OpCode::AttributeAtVertex: {
  1227. Value *Attribute = CI->getArgOperand(DXIL::OperandIndex::kBinarySrc0OpIdx);
  1228. DxilSignature &inputSig = ValCtx.DxilMod.GetInputSignature();
  1229. Value *row = CI->getArgOperand(DXIL::OperandIndex::kLoadInputRowOpIdx);
  1230. Value *col = CI->getArgOperand(DXIL::OperandIndex::kLoadInputColOpIdx);
  1231. DxilSignatureElement *pSE =
  1232. ValidateSignatureAccess(CI, inputSig, Attribute, row, col, ValCtx);
  1233. if (pSE && pSE->GetInterpolationMode()->GetKind() !=
  1234. hlsl::InterpolationMode::Kind::Constant) {
  1235. ValCtx.EmitInstrFormatError(
  1236. CI, ValidationRule::InstrAttributeAtVertexNoInterpolation,
  1237. {pSE->GetName()});
  1238. }
  1239. } break;
  1240. case DXIL::OpCode::GetDimensions: {
  1241. DxilInst_GetDimensions getDim(CI);
  1242. Value *handle = getDim.get_handle();
  1243. DXIL::ComponentType compTy;
  1244. DXIL::ResourceClass resClass;
  1245. unsigned resIndex;
  1246. DXIL::ResourceKind resKind =
  1247. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1248. // Check the result component use.
  1249. ResRetUsage usage;
  1250. CollectGetDimResRetUsage(usage, CI, ValCtx);
  1251. // Mip level only for texture.
  1252. switch (resKind) {
  1253. case DXIL::ResourceKind::Texture1D:
  1254. if (usage.y) {
  1255. ValCtx.EmitInstrFormatError(
  1256. CI, ValidationRule::InstrUndefResultForGetDimension,
  1257. {"y", "Texture1D"});
  1258. }
  1259. if (usage.z) {
  1260. ValCtx.EmitInstrFormatError(
  1261. CI, ValidationRule::InstrUndefResultForGetDimension,
  1262. {"z", "Texture1D"});
  1263. }
  1264. break;
  1265. case DXIL::ResourceKind::Texture1DArray:
  1266. if (usage.z) {
  1267. ValCtx.EmitInstrFormatError(
  1268. CI, ValidationRule::InstrUndefResultForGetDimension,
  1269. {"z", "Texture1DArray"});
  1270. }
  1271. break;
  1272. case DXIL::ResourceKind::Texture2D:
  1273. if (usage.z) {
  1274. ValCtx.EmitInstrFormatError(
  1275. CI, ValidationRule::InstrUndefResultForGetDimension,
  1276. {"z", "Texture2D"});
  1277. }
  1278. break;
  1279. case DXIL::ResourceKind::Texture2DArray:
  1280. break;
  1281. case DXIL::ResourceKind::Texture2DMS:
  1282. if (usage.z) {
  1283. ValCtx.EmitInstrFormatError(
  1284. CI, ValidationRule::InstrUndefResultForGetDimension,
  1285. {"z", "Texture2DMS"});
  1286. }
  1287. break;
  1288. case DXIL::ResourceKind::Texture2DMSArray:
  1289. break;
  1290. case DXIL::ResourceKind::Texture3D:
  1291. break;
  1292. case DXIL::ResourceKind::TextureCube:
  1293. if (usage.z) {
  1294. ValCtx.EmitInstrFormatError(
  1295. CI, ValidationRule::InstrUndefResultForGetDimension,
  1296. {"z", "TextureCube"});
  1297. }
  1298. break;
  1299. case DXIL::ResourceKind::TextureCubeArray:
  1300. break;
  1301. case DXIL::ResourceKind::StructuredBuffer:
  1302. case DXIL::ResourceKind::RawBuffer:
  1303. case DXIL::ResourceKind::TypedBuffer:
  1304. case DXIL::ResourceKind::TBuffer: {
  1305. Value *mip = getDim.get_mipLevel();
  1306. if (!isa<UndefValue>(mip)) {
  1307. ValCtx.EmitInstrError(
  1308. CI, ValidationRule::InstrMipLevelForGetDimension);
  1309. }
  1310. if (resKind != DXIL::ResourceKind::Invalid) {
  1311. if (usage.y || usage.z || usage.w) {
  1312. ValCtx.EmitInstrFormatError(
  1313. CI, ValidationRule::InstrUndefResultForGetDimension,
  1314. {"invalid", "resource"});
  1315. }
  1316. }
  1317. } break;
  1318. default: {
  1319. ValCtx.EmitInstrError(
  1320. CI, ValidationRule::InstrResourceKindForGetDim);
  1321. } break;
  1322. }
  1323. if (usage.status) {
  1324. ValCtx.EmitInstrFormatError(
  1325. CI, ValidationRule::InstrUndefResultForGetDimension,
  1326. {"invalid", "resource"});
  1327. }
  1328. } break;
  1329. case DXIL::OpCode::CalculateLOD: {
  1330. DxilInst_CalculateLOD lod(CI);
  1331. Value *samplerHandle = lod.get_sampler();
  1332. if (GetSamplerKind(samplerHandle, ValCtx) != DXIL::SamplerKind::Default) {
  1333. ValCtx.EmitInstrError(CI,
  1334. ValidationRule::InstrSamplerModeForLOD);
  1335. }
  1336. Value *handle = lod.get_handle();
  1337. DXIL::ComponentType compTy;
  1338. DXIL::ResourceClass resClass;
  1339. unsigned resIndex;
  1340. DXIL::ResourceKind resKind =
  1341. GetResourceKindAndCompTy(handle, compTy, resClass, resIndex, ValCtx);
  1342. if (resClass != DXIL::ResourceClass::SRV) {
  1343. ValCtx.EmitInstrError(CI,
  1344. ValidationRule::InstrResourceClassForSamplerGather);
  1345. return;
  1346. }
  1347. // Coord match resource.
  1348. ValidateCalcLODResourceDimensionCoord(
  1349. CI, resKind, {lod.get_coord0(), lod.get_coord1(), lod.get_coord2()},
  1350. ValCtx);
  1351. switch (resKind) {
  1352. case DXIL::ResourceKind::Texture1D:
  1353. case DXIL::ResourceKind::Texture1DArray:
  1354. case DXIL::ResourceKind::Texture2D:
  1355. case DXIL::ResourceKind::Texture2DArray:
  1356. case DXIL::ResourceKind::Texture3D:
  1357. case DXIL::ResourceKind::TextureCube:
  1358. case DXIL::ResourceKind::TextureCubeArray:
  1359. break;
  1360. default:
  1361. ValCtx.EmitInstrError(
  1362. CI, ValidationRule::InstrResourceKindForCalcLOD);
  1363. break;
  1364. }
  1365. } break;
  1366. case DXIL::OpCode::TextureGather: {
  1367. DxilInst_TextureGather gather(CI);
  1368. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1369. {gather.get_coord0(), gather.get_coord1(),
  1370. gather.get_coord2(), gather.get_coord3()},
  1371. {gather.get_offset0(), gather.get_offset1()},
  1372. /*IsSampleC*/ false, ValCtx);
  1373. } break;
  1374. case DXIL::OpCode::TextureGatherCmp: {
  1375. DxilInst_TextureGatherCmp gather(CI);
  1376. ValidateGather(CI, gather.get_srv(), gather.get_sampler(),
  1377. {gather.get_coord0(), gather.get_coord1(),
  1378. gather.get_coord2(), gather.get_coord3()},
  1379. {gather.get_offset0(), gather.get_offset1()},
  1380. /*IsSampleC*/ true, ValCtx);
  1381. } break;
  1382. case DXIL::OpCode::Sample: {
  1383. DxilInst_Sample sample(CI);
  1384. ValidateSampleInst(
  1385. CI, sample.get_srv(), sample.get_sampler(),
  1386. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1387. sample.get_coord3()},
  1388. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1389. /*IsSampleC*/ false, ValCtx);
  1390. } break;
  1391. case DXIL::OpCode::SampleCmp: {
  1392. DxilInst_SampleCmp sample(CI);
  1393. ValidateSampleInst(
  1394. CI, sample.get_srv(), sample.get_sampler(),
  1395. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1396. sample.get_coord3()},
  1397. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1398. /*IsSampleC*/ true, ValCtx);
  1399. } break;
  1400. case DXIL::OpCode::SampleCmpLevelZero: {
  1401. // sampler must be comparison mode.
  1402. DxilInst_SampleCmpLevelZero sample(CI);
  1403. ValidateSampleInst(
  1404. CI, sample.get_srv(), sample.get_sampler(),
  1405. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1406. sample.get_coord3()},
  1407. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1408. /*IsSampleC*/ true, ValCtx);
  1409. } break;
  1410. case DXIL::OpCode::SampleBias: {
  1411. DxilInst_SampleBias sample(CI);
  1412. Value *bias = sample.get_bias();
  1413. if (ConstantFP *cBias = dyn_cast<ConstantFP>(bias)) {
  1414. float fBias = cBias->getValueAPF().convertToFloat();
  1415. if (fBias < DXIL::kMinMipLodBias || fBias > DXIL::kMaxMipLodBias) {
  1416. ValCtx.EmitInstrFormatError(
  1417. CI, ValidationRule::InstrImmBiasForSampleB,
  1418. {std::to_string(DXIL::kMinMipLodBias),
  1419. std::to_string(DXIL::kMaxMipLodBias),
  1420. std::to_string(cBias->getValueAPF().convertToFloat())});
  1421. }
  1422. }
  1423. ValidateSampleInst(
  1424. CI, sample.get_srv(), sample.get_sampler(),
  1425. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1426. sample.get_coord3()},
  1427. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1428. /*IsSampleC*/ false, ValCtx);
  1429. } break;
  1430. case DXIL::OpCode::SampleGrad: {
  1431. DxilInst_SampleGrad sample(CI);
  1432. ValidateSampleInst(
  1433. CI, sample.get_srv(), sample.get_sampler(),
  1434. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1435. sample.get_coord3()},
  1436. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1437. /*IsSampleC*/ false, ValCtx);
  1438. } break;
  1439. case DXIL::OpCode::SampleLevel: {
  1440. DxilInst_SampleLevel sample(CI);
  1441. ValidateSampleInst(
  1442. CI, sample.get_srv(), sample.get_sampler(),
  1443. {sample.get_coord0(), sample.get_coord1(), sample.get_coord2(),
  1444. sample.get_coord3()},
  1445. {sample.get_offset0(), sample.get_offset1(), sample.get_offset2()},
  1446. /*IsSampleC*/ false, ValCtx);
  1447. } break;
  1448. case DXIL::OpCode::CheckAccessFullyMapped: {
  1449. Value *Src = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1450. ExtractValueInst *EVI = dyn_cast<ExtractValueInst>(Src);
  1451. if (!EVI) {
  1452. ValCtx.EmitInstrError(CI, ValidationRule::InstrCheckAccessFullyMapped);
  1453. } else {
  1454. Value *V = EVI->getOperand(0);
  1455. bool isLegal = EVI->getNumIndices() == 1 &&
  1456. EVI->getIndices()[0] == DXIL::kResRetStatusIndex &&
  1457. ValCtx.DxilMod.GetOP()->IsResRetType(V->getType());
  1458. if (!isLegal) {
  1459. ValCtx.EmitInstrError(CI, ValidationRule::InstrCheckAccessFullyMapped);
  1460. }
  1461. }
  1462. } break;
  1463. case DXIL::OpCode::Barrier: {
  1464. DxilInst_Barrier barrier(CI);
  1465. Value *mode = barrier.get_barrierMode();
  1466. ConstantInt *cMode = dyn_cast<ConstantInt>(mode);
  1467. if (!cMode) {
  1468. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1469. {"Mode", "Barrier"});
  1470. return;
  1471. }
  1472. const unsigned uglobal =
  1473. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceGlobal);
  1474. const unsigned g = static_cast<unsigned>(DXIL::BarrierMode::TGSMFence);
  1475. const unsigned t =
  1476. static_cast<unsigned>(DXIL::BarrierMode::SyncThreadGroup);
  1477. const unsigned ut =
  1478. static_cast<unsigned>(DXIL::BarrierMode::UAVFenceThreadGroup);
  1479. unsigned barrierMode = cMode->getLimitedValue();
  1480. if (ValCtx.DxilMod.GetShaderModel()->IsCS()) {
  1481. bool bHasUGlobal = barrierMode & uglobal;
  1482. bool bHasGroup = barrierMode & g;
  1483. bool bHasUGroup = barrierMode & ut;
  1484. if (bHasUGlobal && bHasUGroup) {
  1485. ValCtx.EmitInstrError(CI,
  1486. ValidationRule::InstrBarrierModeUselessUGroup);
  1487. }
  1488. if (!bHasUGlobal && !bHasGroup && !bHasUGroup) {
  1489. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeNoMemory);
  1490. }
  1491. } else {
  1492. if (uglobal != barrierMode) {
  1493. ValCtx.EmitInstrError(CI, ValidationRule::InstrBarrierModeForNonCS);
  1494. }
  1495. }
  1496. } break;
  1497. case DXIL::OpCode::BufferStore: {
  1498. DxilInst_BufferStore bufSt(CI);
  1499. DXIL::ComponentType compTy;
  1500. DXIL::ResourceClass resClass;
  1501. unsigned resIndex;
  1502. DXIL::ResourceKind resKind =
  1503. GetResourceKindAndCompTy(bufSt.get_uav(), compTy, resClass, resIndex, ValCtx);
  1504. if (resClass != DXIL::ResourceClass::UAV) {
  1505. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1506. }
  1507. ConstantInt *mask = dyn_cast<ConstantInt>(bufSt.get_mask());
  1508. if (!mask) {
  1509. // Mask for buffer store should be immediate.
  1510. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "BufferStore"});
  1511. return;
  1512. }
  1513. unsigned uMask = mask->getLimitedValue();
  1514. unsigned stValMask =
  1515. StoreValueToMask({bufSt.get_value0(), bufSt.get_value1(),
  1516. bufSt.get_value2(), bufSt.get_value3()});
  1517. if (stValMask != uMask) {
  1518. ValCtx.EmitInstrFormatError(
  1519. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1520. {std::to_string(uMask), std::to_string(stValMask)});
  1521. }
  1522. Value *offset = bufSt.get_coord1();
  1523. switch (resKind) {
  1524. case DXIL::ResourceKind::RawBuffer:
  1525. if (!isa<UndefValue>(offset)) {
  1526. ValCtx.EmitInstrError(
  1527. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1528. }
  1529. break;
  1530. case DXIL::ResourceKind::TypedBuffer:
  1531. case DXIL::ResourceKind::TBuffer:
  1532. if (!isa<UndefValue>(offset)) {
  1533. ValCtx.EmitInstrError(
  1534. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1535. }
  1536. if (uMask != 0xf) {
  1537. ValCtx.EmitInstrError(
  1538. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1539. }
  1540. break;
  1541. case DXIL::ResourceKind::StructuredBuffer:
  1542. if (isa<UndefValue>(offset)) {
  1543. ValCtx.EmitInstrError(
  1544. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1545. }
  1546. break;
  1547. default:
  1548. ValCtx.EmitInstrError(
  1549. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1550. break;
  1551. }
  1552. } break;
  1553. case DXIL::OpCode::TextureStore: {
  1554. DxilInst_TextureStore texSt(CI);
  1555. DXIL::ComponentType compTy;
  1556. DXIL::ResourceClass resClass;
  1557. unsigned resIndex;
  1558. DXIL::ResourceKind resKind =
  1559. GetResourceKindAndCompTy(texSt.get_srv(), compTy, resClass, resIndex, ValCtx);
  1560. if (resClass != DXIL::ResourceClass::UAV) {
  1561. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForUAVStore);
  1562. }
  1563. ConstantInt *mask = dyn_cast<ConstantInt>(texSt.get_mask());
  1564. if (!mask) {
  1565. // Mask for buffer store should be immediate.
  1566. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"Mask", "TextureStore"});
  1567. return;
  1568. }
  1569. unsigned uMask = mask->getLimitedValue();
  1570. if (uMask != 0xf) {
  1571. ValCtx.EmitInstrError(
  1572. CI, ValidationRule::InstrWriteMaskForTypedUAVStore);
  1573. }
  1574. unsigned stValMask =
  1575. StoreValueToMask({texSt.get_value0(), texSt.get_value1(),
  1576. texSt.get_value2(), texSt.get_value3()});
  1577. if (stValMask != uMask) {
  1578. ValCtx.EmitInstrFormatError(
  1579. CI, ValidationRule::InstrWriteMaskMatchValueForUAVStore,
  1580. {std::to_string(uMask), std::to_string(stValMask)});
  1581. }
  1582. switch (resKind) {
  1583. case DXIL::ResourceKind::Texture1D:
  1584. case DXIL::ResourceKind::Texture1DArray:
  1585. case DXIL::ResourceKind::Texture2D:
  1586. case DXIL::ResourceKind::Texture2DArray:
  1587. case DXIL::ResourceKind::Texture3D:
  1588. break;
  1589. default:
  1590. ValCtx.EmitInstrError(
  1591. CI, ValidationRule::InstrResourceKindForTextureStore);
  1592. break;
  1593. }
  1594. } break;
  1595. case DXIL::OpCode::BufferLoad: {
  1596. DxilInst_BufferLoad bufLd(CI);
  1597. DXIL::ComponentType compTy;
  1598. DXIL::ResourceClass resClass;
  1599. unsigned resIndex;
  1600. DXIL::ResourceKind resKind =
  1601. GetResourceKindAndCompTy(bufLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1602. if (resClass != DXIL::ResourceClass::SRV &&
  1603. resClass != DXIL::ResourceClass::UAV) {
  1604. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1605. }
  1606. Value *offset = bufLd.get_wot();
  1607. switch (resKind) {
  1608. case DXIL::ResourceKind::RawBuffer:
  1609. case DXIL::ResourceKind::TypedBuffer:
  1610. case DXIL::ResourceKind::TBuffer:
  1611. if (!isa<UndefValue>(offset)) {
  1612. ValCtx.EmitInstrError(
  1613. CI, ValidationRule::InstrCoordinateCountForRawTypedBuf);
  1614. }
  1615. break;
  1616. case DXIL::ResourceKind::StructuredBuffer:
  1617. if (isa<UndefValue>(offset)) {
  1618. ValCtx.EmitInstrError(
  1619. CI, ValidationRule::InstrCoordinateCountForStructBuf);
  1620. }
  1621. break;
  1622. default:
  1623. ValCtx.EmitInstrError(
  1624. CI, ValidationRule::InstrResourceKindForBufferLoadStore);
  1625. break;
  1626. }
  1627. } break;
  1628. case DXIL::OpCode::TextureLoad: {
  1629. DxilInst_TextureLoad texLd(CI);
  1630. DXIL::ComponentType compTy;
  1631. DXIL::ResourceClass resClass;
  1632. unsigned resIndex;
  1633. DXIL::ResourceKind resKind =
  1634. GetResourceKindAndCompTy(texLd.get_srv(), compTy, resClass, resIndex, ValCtx);
  1635. Value *mipLevel = texLd.get_mipLevelOrSampleCount();
  1636. if (resClass == DXIL::ResourceClass::UAV) {
  1637. bool noOffset = isa<UndefValue>(texLd.get_offset0());
  1638. noOffset &= isa<UndefValue>(texLd.get_offset1());
  1639. noOffset &= isa<UndefValue>(texLd.get_offset2());
  1640. if (!noOffset) {
  1641. ValCtx.EmitInstrError(CI,
  1642. ValidationRule::InstrOffsetOnUAVLoad);
  1643. }
  1644. if (!isa<UndefValue>(mipLevel)) {
  1645. ValCtx.EmitInstrError(CI, ValidationRule::InstrMipOnUAVLoad);
  1646. }
  1647. } else {
  1648. if (resClass != DXIL::ResourceClass::SRV) {
  1649. ValCtx.EmitInstrError(CI, ValidationRule::InstrResourceClassForLoad);
  1650. }
  1651. }
  1652. switch (resKind) {
  1653. case DXIL::ResourceKind::Texture1D:
  1654. case DXIL::ResourceKind::Texture1DArray:
  1655. case DXIL::ResourceKind::Texture2D:
  1656. case DXIL::ResourceKind::Texture2DArray:
  1657. case DXIL::ResourceKind::Texture3D:
  1658. break;
  1659. case DXIL::ResourceKind::Texture2DMS:
  1660. case DXIL::ResourceKind::Texture2DMSArray: {
  1661. if (isa<UndefValue>(mipLevel)) {
  1662. ValCtx.EmitInstrError(
  1663. CI, ValidationRule::InstrSampleIndexForLoad2DMS);
  1664. }
  1665. } break;
  1666. default:
  1667. ValCtx.EmitInstrError(
  1668. CI, ValidationRule::InstrResourceKindForTextureLoad);
  1669. break;
  1670. }
  1671. } break;
  1672. case DXIL::OpCode::CutStream:
  1673. case DXIL::OpCode::EmitThenCutStream:
  1674. case DXIL::OpCode::EmitStream: {
  1675. if (pSM->IsGS()) {
  1676. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  1677. Value *streamID =
  1678. CI->getArgOperand(DXIL::OperandIndex::kStreamEmitCutIDOpIdx);
  1679. if (ConstantInt *cStreamID = dyn_cast<ConstantInt>(streamID)) {
  1680. int immStreamID = cStreamID->getValue().getLimitedValue();
  1681. if (cStreamID->getValue().isNegative() || immStreamID >= 4) {
  1682. ValCtx.EmitOperandOutOfRange(CI, "StreamID","0~4",
  1683. std::to_string(immStreamID));
  1684. } else {
  1685. unsigned immMask = 1 << immStreamID;
  1686. if ((streamMask & immMask) == 0) {
  1687. std::string range;
  1688. for (unsigned i = 0; i < 4; i++) {
  1689. if (streamMask & (1 << i)) {
  1690. range += std::to_string(i) + " ";
  1691. }
  1692. }
  1693. ValCtx.EmitOperandOutOfRange(CI, "StreamID", range,
  1694. std::to_string(immStreamID));
  1695. }
  1696. }
  1697. } else {
  1698. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst,
  1699. {"StreamID", "Emit/CutStream"});
  1700. }
  1701. } else {
  1702. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcodeInInvalidFunction,
  1703. {"Emit/CutStream", "Geometry shader"});
  1704. }
  1705. } break;
  1706. case DXIL::OpCode::BufferUpdateCounter: {
  1707. DxilInst_BufferUpdateCounter updateCounter(CI);
  1708. DXIL::ComponentType compTy;
  1709. DXIL::ResourceClass resClass;
  1710. unsigned resIndex;
  1711. DXIL::ResourceKind resKind =
  1712. GetResourceKindAndCompTy(updateCounter.get_uav(), compTy, resClass, resIndex, ValCtx);
  1713. if (resClass != DXIL::ResourceClass::UAV) {
  1714. ValCtx.EmitInstrError(CI,
  1715. ValidationRule::InstrBufferUpdateCounterOnUAV);
  1716. }
  1717. if (resKind != DXIL::ResourceKind::StructuredBuffer) {
  1718. ValCtx.EmitInstrError(CI,
  1719. ValidationRule::SmCounterOnlyOnStructBuf);
  1720. }
  1721. Value *inc = updateCounter.get_inc();
  1722. if (ConstantInt *cInc = dyn_cast<ConstantInt>(inc)) {
  1723. bool isInc = cInc->getLimitedValue() == 1;
  1724. if (ValCtx.UavCounterIncMap.count(resIndex)) {
  1725. if (isInc != ValCtx.UavCounterIncMap[resIndex]) {
  1726. ValCtx.EmitInstrError(CI, ValidationRule::InstrOnlyOneAllocConsume);
  1727. }
  1728. }
  1729. else {
  1730. ValCtx.UavCounterIncMap[resIndex] = isInc;
  1731. }
  1732. } else {
  1733. ValCtx.EmitInstrFormatError(CI, ValidationRule::InstrOpConst, {"inc", "BufferUpdateCounter"});
  1734. }
  1735. } break;
  1736. case DXIL::OpCode::Asin: {
  1737. DxilInst_Asin I(CI);
  1738. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1739. if (imm->getValueAPF().isInfinity()) {
  1740. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAsin);
  1741. }
  1742. }
  1743. } break;
  1744. case DXIL::OpCode::Acos: {
  1745. DxilInst_Acos I(CI);
  1746. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1747. if (imm->getValueAPF().isInfinity()) {
  1748. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteAcos);
  1749. }
  1750. }
  1751. } break;
  1752. case DXIL::OpCode::Log: {
  1753. DxilInst_Log I(CI);
  1754. if (ConstantFP *imm = dyn_cast<ConstantFP>(I.get_value())) {
  1755. if (imm->getValueAPF().isInfinity()) {
  1756. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteLog);
  1757. }
  1758. }
  1759. } break;
  1760. case DXIL::OpCode::DerivFineX:
  1761. case DXIL::OpCode::DerivFineY:
  1762. case DXIL::OpCode::DerivCoarseX:
  1763. case DXIL::OpCode::DerivCoarseY: {
  1764. Value *V = CI->getArgOperand(DXIL::OperandIndex::kUnarySrc0OpIdx);
  1765. if (ConstantFP *imm = dyn_cast<ConstantFP>(V)) {
  1766. if (imm->getValueAPF().isInfinity()) {
  1767. ValCtx.EmitInstrError(CI, ValidationRule::InstrNoIndefiniteDsxy);
  1768. }
  1769. }
  1770. } break;
  1771. case DXIL::OpCode::Coverage:
  1772. ValCtx.m_bCoverageIn = true;
  1773. break;
  1774. case DXIL::OpCode::InnerCoverage:
  1775. ValCtx.m_bInnerCoverageIn = true;
  1776. break;
  1777. case DXIL::OpCode::ViewID:
  1778. ValCtx.hasViewID = true;
  1779. break;
  1780. default:
  1781. // Skip opcodes don't need special check.
  1782. break;
  1783. }
  1784. if (ValCtx.m_bCoverageIn && ValCtx.m_bInnerCoverageIn) {
  1785. ValCtx.EmitError(ValidationRule::SmPSCoverageAndInnerCoverage);
  1786. }
  1787. }
  1788. static bool IsDxilFunction(llvm::Function *F) {
  1789. unsigned argSize = F->arg_size();
  1790. if (argSize < 1) {
  1791. // Cannot be a DXIL operation.
  1792. return false;
  1793. }
  1794. return OP::IsDxilOpFunc(F);
  1795. }
  1796. static void ValidateExternalFunction(Function *F, ValidationContext &ValCtx) {
  1797. if (!IsDxilFunction(F)) {
  1798. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclDxilFnExtern);
  1799. return;
  1800. }
  1801. if (F->use_empty()) {
  1802. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclUsedExternalFunction);
  1803. return;
  1804. }
  1805. const ShaderModel *pSM = ValCtx.DxilMod.GetShaderModel();
  1806. OP *hlslOP = ValCtx.DxilMod.GetOP();
  1807. Type *voidTy = Type::getVoidTy(F->getContext());
  1808. for (User *user : F->users()) {
  1809. CallInst *CI = dyn_cast<CallInst>(user);
  1810. if (!CI) {
  1811. ValCtx.EmitGlobalValueError(F, ValidationRule::DeclFnIsCalled);
  1812. continue;
  1813. }
  1814. Value *argOpcode = CI->getArgOperand(0);
  1815. ConstantInt *constOpcode = dyn_cast<ConstantInt>(argOpcode);
  1816. if (!constOpcode) {
  1817. // opcode not immediate; function body will validate this error.
  1818. continue;
  1819. }
  1820. unsigned opcode = constOpcode->getLimitedValue();
  1821. if (opcode >= (unsigned)DXIL::OpCode::NumOpCodes) {
  1822. // invalid opcode; function body will validate this error.
  1823. continue;
  1824. }
  1825. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  1826. // In some cases, no overloads are provided (void is exclusive to others)
  1827. Function *dxilFunc;
  1828. if (hlslOP->IsOverloadLegal(dxilOpcode, voidTy)) {
  1829. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, voidTy);
  1830. }
  1831. else {
  1832. Type *Ty = hlslOP->GetOverloadType(dxilOpcode, CI->getCalledFunction());
  1833. try {
  1834. if (!hlslOP->IsOverloadLegal(dxilOpcode, Ty)) {
  1835. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1836. continue;
  1837. }
  1838. }
  1839. catch (...) {
  1840. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1841. continue;
  1842. }
  1843. dxilFunc = hlslOP->GetOpFunc(dxilOpcode, Ty->getScalarType());
  1844. }
  1845. if (!dxilFunc) {
  1846. // Cannot find dxilFunction based on opcode and type.
  1847. ValCtx.EmitInstrError(CI, ValidationRule::InstrOload);
  1848. continue;
  1849. }
  1850. if (dxilFunc->getFunctionType() != F->getFunctionType()) {
  1851. ValCtx.EmitGlobalValueError(dxilFunc, ValidationRule::InstrCallOload);
  1852. continue;
  1853. }
  1854. if (!ValidateOpcodeInProfile(dxilOpcode, pSM)) {
  1855. // Opcode not available in profile.
  1856. ValCtx.EmitInstrFormatError(CI, ValidationRule::SmOpcode,
  1857. {hlslOP->GetOpCodeName(dxilOpcode),
  1858. pSM->GetName()});
  1859. continue;
  1860. }
  1861. // Check more detail.
  1862. ValidateDxilOperationCallInProfile(CI, dxilOpcode, pSM, ValCtx);
  1863. }
  1864. }
  1865. ///////////////////////////////////////////////////////////////////////////////
  1866. // Instruction validation functions. //
  1867. static bool IsLLVMInstructionAllowed(llvm::Instruction &I) {
  1868. unsigned op = I.getOpcode();
  1869. /* <py::lines('OPCODE-ALLOWED')>hctdb_instrhelp.get_instrs_pred("op", lambda i: not i.is_dxil_op and i.is_allowed, "llvm_id")</py>*/
  1870. // OPCODE-ALLOWED:BEGIN
  1871. // Instructions: Ret=1, Br=2, Switch=3, Add=8, FAdd=9, Sub=10, FSub=11, Mul=12,
  1872. // FMul=13, UDiv=14, SDiv=15, FDiv=16, URem=17, SRem=18, FRem=19, Shl=20,
  1873. // LShr=21, AShr=22, And=23, Or=24, Xor=25, Alloca=26, Load=27, Store=28,
  1874. // GetElementPtr=29, AtomicCmpXchg=31, AtomicRMW=32, Trunc=33, ZExt=34,
  1875. // SExt=35, FPToUI=36, FPToSI=37, UIToFP=38, SIToFP=39, FPTrunc=40, FPExt=41,
  1876. // BitCast=44, AddrSpaceCast=45, ICmp=46, FCmp=47, PHI=48, Call=49, Select=50,
  1877. // ExtractValue=57
  1878. return 1 <= op && op <= 3 || 8 <= op && op <= 29 || 31 <= op && op <= 41 || 44 <= op && op <= 50 || op == 57;
  1879. // OPCODE-ALLOWED:END
  1880. }
  1881. static bool IsDxilBuiltinStructType(StructType *ST, hlsl::OP *hlslOP) {
  1882. if (ST == hlslOP->GetBinaryWithCarryType())
  1883. return true;
  1884. if (ST == hlslOP->GetBinaryWithTwoOutputsType())
  1885. return true;
  1886. if (ST == hlslOP->GetInt4Type())
  1887. return true;
  1888. if (ST == hlslOP->GetDimensionsType())
  1889. return true;
  1890. if (ST == hlslOP->GetHandleType())
  1891. return true;
  1892. if (ST == hlslOP->GetSamplePosType())
  1893. return true;
  1894. if (ST == hlslOP->GetSplitDoubleType())
  1895. return true;
  1896. unsigned EltNum = ST->getNumElements();
  1897. switch (EltNum) {
  1898. case 2:
  1899. case 4:
  1900. case 8: { // 2 for doubles, 8 for halfs.
  1901. Type *EltTy = ST->getElementType(0);
  1902. return ST == hlslOP->GetCBufferRetType(EltTy);
  1903. } break;
  1904. case 5: {
  1905. Type *EltTy = ST->getElementType(0);
  1906. return ST == hlslOP->GetResRetType(EltTy);
  1907. } break;
  1908. default:
  1909. return false;
  1910. }
  1911. }
  1912. static bool ValidateType(Type *Ty, ValidationContext &ValCtx) {
  1913. DXASSERT_NOMSG(Ty != nullptr);
  1914. if (Ty->isPointerTy()) {
  1915. return ValidateType(Ty->getPointerElementType(), ValCtx);
  1916. }
  1917. if (Ty->isArrayTy()) {
  1918. Type *EltTy = Ty->getArrayElementType();
  1919. if (isa<ArrayType>(EltTy)) {
  1920. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoMultiDim);
  1921. return false;
  1922. }
  1923. return ValidateType(EltTy, ValCtx);
  1924. }
  1925. if (Ty->isStructTy()) {
  1926. bool result = true;
  1927. StructType *ST = cast<StructType>(Ty);
  1928. StringRef Name = ST->getName();
  1929. if (Name.startswith("dx.")) {
  1930. hlsl::OP *hlslOP = ValCtx.DxilMod.GetOP();
  1931. if (IsDxilBuiltinStructType(ST, hlslOP)) {
  1932. ValCtx.EmitTypeError(Ty, ValidationRule::InstrDxilStructUser);
  1933. result = false;
  1934. }
  1935. ValCtx.EmitTypeError(Ty, ValidationRule::DeclDxilNsReserved);
  1936. result = false;
  1937. }
  1938. for (auto e : ST->elements()) {
  1939. if (!ValidateType(e, ValCtx)) {
  1940. result = false;
  1941. }
  1942. }
  1943. return result;
  1944. }
  1945. if (Ty->isFloatTy() || Ty->isHalfTy() || Ty->isDoubleTy()) {
  1946. return true;
  1947. }
  1948. if (Ty->isIntegerTy()) {
  1949. unsigned width = Ty->getIntegerBitWidth();
  1950. if (width != 1 && width != 8 && width != 16 && width != 32 && width != 64) {
  1951. ValCtx.EmitTypeError(Ty, ValidationRule::TypesIntWidth);
  1952. return false;
  1953. }
  1954. return true;
  1955. }
  1956. if (Ty->isVectorTy()) {
  1957. ValCtx.EmitTypeError(Ty, ValidationRule::TypesNoVector);
  1958. return false;
  1959. }
  1960. ValCtx.EmitTypeError(Ty, ValidationRule::TypesDefined);
  1961. return false;
  1962. }
  1963. static bool GetNodeOperandAsInt(ValidationContext &ValCtx, MDNode *pMD, unsigned index, uint64_t *pValue) {
  1964. *pValue = 0;
  1965. if (pMD->getNumOperands() < index) {
  1966. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1967. return false;
  1968. }
  1969. ConstantAsMetadata *C = dyn_cast<ConstantAsMetadata>(pMD->getOperand(index));
  1970. if (C == nullptr) {
  1971. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1972. return false;
  1973. }
  1974. ConstantInt *CI = dyn_cast<ConstantInt>(C->getValue());
  1975. if (CI == nullptr) {
  1976. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1977. return false;
  1978. }
  1979. *pValue = CI->getValue().getZExtValue();
  1980. return true;
  1981. }
  1982. static bool IsPrecise(Instruction &I, ValidationContext &ValCtx) {
  1983. MDNode *pMD = I.getMetadata(DxilMDHelper::kDxilPreciseAttributeMDName);
  1984. if (pMD == nullptr) {
  1985. return false;
  1986. }
  1987. if (pMD->getNumOperands() != 1) {
  1988. ValCtx.EmitMetaError(pMD, ValidationRule::MetaWellFormed);
  1989. return false;
  1990. }
  1991. uint64_t val;
  1992. if (!GetNodeOperandAsInt(ValCtx, pMD, 0, &val)) {
  1993. return false;
  1994. }
  1995. if (val == 1) {
  1996. return true;
  1997. }
  1998. if (val != 0) {
  1999. ValCtx.EmitMetaError(pMD, ValidationRule::MetaValueRange);
  2000. }
  2001. return false;
  2002. }
  2003. static bool IsValueMinPrec(DxilModule &DxilMod, Value *V) {
  2004. DXASSERT(DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision,
  2005. "else caller didn't check - currently this path should never be hit "
  2006. "otherwise");
  2007. (DxilMod);
  2008. Type *Ty = V->getType();
  2009. if (Ty->isIntegerTy()) {
  2010. return 16 == Ty->getIntegerBitWidth();
  2011. }
  2012. return Ty->isHalfTy();
  2013. }
  2014. static void ValidateGradientOps(Function *F, ArrayRef<CallInst *> ops, ArrayRef<CallInst *> barriers, ValidationContext &ValCtx) {
  2015. // In the absence of wave operations, the wave validation effect need not happen.
  2016. // We haven't verified this is true at this point, but validation will fail
  2017. // later if the flags don't match in any case. Given that most shaders will
  2018. // not be using these wave operations, it's a reasonable cost saving.
  2019. if (!ValCtx.DxilMod.m_ShaderFlags.GetWaveOps()) {
  2020. return;
  2021. }
  2022. std::unique_ptr<WaveSensitivityAnalysis> WaveVal(WaveSensitivityAnalysis::create());
  2023. WaveVal->Analyze(F);
  2024. for (CallInst *op : ops) {
  2025. if (WaveVal->IsWaveSensitive(op)) {
  2026. ValCtx.EmitInstrError(op, ValidationRule::UniNoWaveSensitiveGradient);
  2027. }
  2028. }
  2029. }
  2030. static void ValidateControlFlowHint(BasicBlock &bb, ValidationContext &ValCtx) {
  2031. // Validate controlflow hint.
  2032. TerminatorInst *TI = bb.getTerminator();
  2033. if (!TI)
  2034. return;
  2035. MDNode *pNode = TI->getMetadata(DxilMDHelper::kDxilControlFlowHintMDName);
  2036. if (!pNode)
  2037. return;
  2038. if (pNode->getNumOperands() < 3)
  2039. return;
  2040. bool bHasBranch = false;
  2041. bool bHasFlatten = false;
  2042. bool bForceCase = false;
  2043. for (unsigned i = 2; i < pNode->getNumOperands(); i++) {
  2044. uint64_t value = 0;
  2045. if (GetNodeOperandAsInt(ValCtx, pNode, i, &value)) {
  2046. DXIL::ControlFlowHint hint = static_cast<DXIL::ControlFlowHint>(value);
  2047. switch (hint) {
  2048. case DXIL::ControlFlowHint::Flatten:
  2049. bHasFlatten = true;
  2050. break;
  2051. case DXIL::ControlFlowHint::Branch:
  2052. bHasBranch = true;
  2053. break;
  2054. case DXIL::ControlFlowHint::ForceCase:
  2055. bForceCase = true;
  2056. break;
  2057. default:
  2058. ValCtx.EmitMetaError(pNode,
  2059. ValidationRule::MetaInvalidControlFlowHint);
  2060. }
  2061. }
  2062. }
  2063. if (bHasBranch && bHasFlatten) {
  2064. ValCtx.EmitMetaError(pNode, ValidationRule::MetaBranchFlatten);
  2065. }
  2066. if (bForceCase && !isa<SwitchInst>(TI)) {
  2067. ValCtx.EmitMetaError(pNode, ValidationRule::MetaForceCaseOnSwitch);
  2068. }
  2069. }
  2070. static void ValidateTBAAMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2071. switch (Node->getNumOperands()) {
  2072. case 1: {
  2073. if (Node->getOperand(0)->getMetadataID() != Metadata::MDStringKind) {
  2074. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2075. }
  2076. } break;
  2077. case 2: {
  2078. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2079. if (!rootNode) {
  2080. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2081. } else {
  2082. ValidateTBAAMetadata(rootNode, ValCtx);
  2083. }
  2084. } break;
  2085. case 3: {
  2086. MDNode *rootNode = dyn_cast<MDNode>(Node->getOperand(1));
  2087. if (!rootNode) {
  2088. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2089. } else {
  2090. ValidateTBAAMetadata(rootNode, ValCtx);
  2091. }
  2092. ConstantAsMetadata *pointsToConstMem = dyn_cast<ConstantAsMetadata>(Node->getOperand(2));
  2093. if (!pointsToConstMem) {
  2094. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2095. } else {
  2096. ConstantInt *isConst = dyn_cast<ConstantInt>(pointsToConstMem->getValue());
  2097. if (!isConst) {
  2098. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2099. } else if (isConst->getValue().getLimitedValue() > 1) {
  2100. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2101. }
  2102. }
  2103. } break;
  2104. default:
  2105. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2106. }
  2107. }
  2108. static void ValidateLoopMetadata(MDNode *Node, ValidationContext &ValCtx) {
  2109. if (Node->getNumOperands() == 0 || Node->getNumOperands() > 2) {
  2110. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2111. return;
  2112. }
  2113. if (Node != Node->getOperand(0).get()) {
  2114. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2115. return;
  2116. }
  2117. if (Node->getNumOperands() == 1) {
  2118. return;
  2119. }
  2120. MDNode *LoopNode = dyn_cast<MDNode>(Node->getOperand(1).get());
  2121. if (!LoopNode) {
  2122. ValCtx.EmitMetaError(Node, ValidationRule::MetaWellFormed);
  2123. return;
  2124. }
  2125. if (LoopNode->getNumOperands() < 1 || LoopNode->getNumOperands() > 2) {
  2126. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2127. return;
  2128. }
  2129. if (LoopNode->getOperand(0) == LoopNode) {
  2130. ValidateLoopMetadata(LoopNode, ValCtx);
  2131. return;
  2132. }
  2133. MDString *LoopStr = dyn_cast<MDString>(LoopNode->getOperand(0));
  2134. if (!LoopStr) {
  2135. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2136. return;
  2137. }
  2138. StringRef Name = LoopStr->getString();
  2139. if (Name != "llvm.loop.unroll.full" && Name != "llvm.loop.unroll.disable" &&
  2140. Name != "llvm.loop.unroll.count") {
  2141. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2142. return;
  2143. }
  2144. if (Name == "llvm.loop.unroll.count") {
  2145. if (LoopNode->getNumOperands() != 2) {
  2146. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2147. return;
  2148. }
  2149. ConstantAsMetadata *CountNode =
  2150. dyn_cast<ConstantAsMetadata>(LoopNode->getOperand(1));
  2151. if (!CountNode) {
  2152. ValCtx.EmitMetaError(LoopNode, ValidationRule::MetaWellFormed);
  2153. } else {
  2154. ConstantInt *Count = dyn_cast<ConstantInt>(CountNode->getValue());
  2155. if (!Count) {
  2156. ValCtx.EmitMetaError(CountNode, ValidationRule::MetaWellFormed);
  2157. }
  2158. }
  2159. }
  2160. }
  2161. static void ValidateInstructionMetadata(Instruction *I,
  2162. ValidationContext &ValCtx) {
  2163. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2164. I->getAllMetadataOtherThanDebugLoc(MDNodes);
  2165. for (auto &MD : MDNodes) {
  2166. if (MD.first == ValCtx.kDxilControlFlowHintMDKind) {
  2167. if (!isa<TerminatorInst>(I)) {
  2168. ValCtx.EmitInstrError(
  2169. I, ValidationRule::MetaControlFlowHintNotOnControlFlow);
  2170. }
  2171. } else if (MD.first == ValCtx.kDxilPreciseMDKind) {
  2172. // Validated in IsPrecise.
  2173. } else if (MD.first == ValCtx.kLLVMLoopMDKind) {
  2174. ValidateLoopMetadata(MD.second, ValCtx);
  2175. } else if (MD.first == LLVMContext::MD_tbaa) {
  2176. ValidateTBAAMetadata(MD.second, ValCtx);
  2177. } else if (MD.first == LLVMContext::MD_range) {
  2178. // Validated in Verifier.cpp.
  2179. } else if (MD.first == LLVMContext::MD_noalias ||
  2180. MD.first == LLVMContext::MD_alias_scope) {
  2181. // noalias for DXIL validator >= 1.2
  2182. } else {
  2183. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2184. }
  2185. }
  2186. }
  2187. static void ValidateFunctionAttribute(Function *F, ValidationContext &ValCtx) {
  2188. AttributeSet attrSet = F->getAttributes();
  2189. // fp32-denorm-mode
  2190. if (attrSet.hasAttribute(AttributeSet::FunctionIndex, DXIL::kFP32DenormKindString)) {
  2191. Attribute attr = attrSet.getAttribute(AttributeSet::FunctionIndex, DXIL::kFP32DenormKindString);
  2192. StringRef value = attr.getValueAsString();
  2193. if (!value.equals(DXIL::kFP32DenormValueAnyString) &&
  2194. !value.equals(DXIL::kFP32DenormValueFtzString) &&
  2195. !value.equals(DXIL::kFP32DenormValuePreserveString))
  2196. {
  2197. ValCtx.EmitFnAttributeError(F, attr.getKindAsString(), attr.getValueAsString());
  2198. }
  2199. }
  2200. }
  2201. static void ValidateFunctionMetadata(Function *F, ValidationContext &ValCtx) {
  2202. SmallVector<std::pair<unsigned, MDNode *>, 2> MDNodes;
  2203. F->getAllMetadata(MDNodes);
  2204. for (auto &MD : MDNodes) {
  2205. ValCtx.EmitMetaError(MD.second, ValidationRule::MetaUsed);
  2206. }
  2207. }
  2208. static void ValidateFunctionBody(Function *F, ValidationContext &ValCtx) {
  2209. bool SupportsMinPrecision =
  2210. ValCtx.DxilMod.GetGlobalFlags() & DXIL::kEnableMinPrecision;
  2211. SmallVector<CallInst *, 16> gradientOps;
  2212. SmallVector<CallInst *, 16> barriers;
  2213. for (auto b = F->begin(), bend = F->end(); b != bend; ++b) {
  2214. for (auto i = b->begin(), iend = b->end(); i != iend; ++i) {
  2215. llvm::Instruction &I = *i;
  2216. if (I.hasMetadata()) {
  2217. ValidateInstructionMetadata(&I, ValCtx);
  2218. }
  2219. // Instructions must be allowed.
  2220. if (!IsLLVMInstructionAllowed(I)) {
  2221. ValCtx.EmitInstrError(&I, ValidationRule::InstrAllowed);
  2222. continue;
  2223. }
  2224. // Instructions marked precise may not have minprecision arguments.
  2225. if (SupportsMinPrecision) {
  2226. if (IsPrecise(I, ValCtx)) {
  2227. for (auto &O : I.operands()) {
  2228. if (IsValueMinPrec(ValCtx.DxilMod, O)) {
  2229. ValCtx.EmitInstrError(
  2230. &I, ValidationRule::InstrMinPrecisionNotPrecise);
  2231. break;
  2232. }
  2233. }
  2234. }
  2235. }
  2236. // Calls to external functions.
  2237. CallInst *CI = dyn_cast<CallInst>(&I);
  2238. if (CI) {
  2239. Function *FCalled = CI->getCalledFunction();
  2240. if (FCalled->isDeclaration()) {
  2241. // External function validation will diagnose.
  2242. if (!IsDxilFunction(FCalled)) {
  2243. continue;
  2244. }
  2245. Value *opcodeVal = CI->getOperand(0);
  2246. ConstantInt *OpcodeConst = dyn_cast<ConstantInt>(opcodeVal);
  2247. if (OpcodeConst == nullptr) {
  2248. ValCtx.EmitInstrFormatError(&I, ValidationRule::InstrOpConst,
  2249. {"Opcode", "DXIL operation"});
  2250. continue;
  2251. }
  2252. unsigned opcode = OpcodeConst->getLimitedValue();
  2253. DXIL::OpCode dxilOpcode = (DXIL::OpCode)opcode;
  2254. if (OP::IsDxilOpGradient(dxilOpcode)) {
  2255. gradientOps.push_back(CI);
  2256. }
  2257. if (dxilOpcode == DXIL::OpCode::Barrier) {
  2258. barriers.push_back(CI);
  2259. }
  2260. // External function validation will check the parameter
  2261. // list. This function will check that the call does not
  2262. // violate any rules.
  2263. }
  2264. continue;
  2265. }
  2266. for (Value *op : I.operands()) {
  2267. if (!isa<PHINode>(&I) && isa<UndefValue>(op)) {
  2268. ValCtx.EmitInstrError(&I,
  2269. ValidationRule::InstrNoReadingUninitialized);
  2270. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(op)) {
  2271. for (Value *opCE : CE->operands()) {
  2272. if (isa<UndefValue>(opCE)) {
  2273. ValCtx.EmitInstrError(
  2274. &I, ValidationRule::InstrNoReadingUninitialized);
  2275. }
  2276. }
  2277. }
  2278. if (IntegerType *IT = dyn_cast<IntegerType>(op->getType())) {
  2279. if (IT->getBitWidth() == 8) {
  2280. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2281. }
  2282. }
  2283. }
  2284. Type *Ty = I.getType();
  2285. if (isa<PointerType>(Ty))
  2286. Ty = Ty->getPointerElementType();
  2287. while (isa<ArrayType>(Ty))
  2288. Ty = Ty->getArrayElementType();
  2289. if (IntegerType *IT = dyn_cast<IntegerType>(Ty)) {
  2290. if (IT->getBitWidth() == 8) {
  2291. ValCtx.EmitInstrError(&I, ValidationRule::TypesI8);
  2292. }
  2293. }
  2294. unsigned opcode = I.getOpcode();
  2295. switch (opcode) {
  2296. case Instruction::Alloca: {
  2297. AllocaInst *AI = cast<AllocaInst>(&I);
  2298. // TODO: validate address space and alignment
  2299. Type *Ty = AI->getAllocatedType();
  2300. if (!ValidateType(Ty, ValCtx)) {
  2301. continue;
  2302. }
  2303. } break;
  2304. case Instruction::ExtractValue: {
  2305. ExtractValueInst *EV = cast<ExtractValueInst>(&I);
  2306. Type *Ty = EV->getAggregateOperand()->getType();
  2307. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2308. Value *Agg = EV->getAggregateOperand();
  2309. if (!isa<AtomicCmpXchgInst>(Agg) &&
  2310. !IsDxilBuiltinStructType(ST, ValCtx.DxilMod.GetOP())) {
  2311. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2312. }
  2313. } else {
  2314. ValCtx.EmitInstrError(EV, ValidationRule::InstrExtractValue);
  2315. }
  2316. } break;
  2317. case Instruction::Load: {
  2318. Type *Ty = I.getType();
  2319. if (!ValidateType(Ty, ValCtx)) {
  2320. continue;
  2321. }
  2322. } break;
  2323. case Instruction::Store: {
  2324. StoreInst *SI = cast<StoreInst>(&I);
  2325. Type *Ty = SI->getValueOperand()->getType();
  2326. if (!ValidateType(Ty, ValCtx)) {
  2327. continue;
  2328. }
  2329. } break;
  2330. case Instruction::GetElementPtr: {
  2331. Type *Ty = I.getType()->getPointerElementType();
  2332. if (!ValidateType(Ty, ValCtx)) {
  2333. continue;
  2334. }
  2335. GetElementPtrInst *GEP = cast<GetElementPtrInst>(&I);
  2336. bool allImmIndex = true;
  2337. for (auto Idx = GEP->idx_begin(), E = GEP->idx_end(); Idx != E; Idx++) {
  2338. if (!isa<ConstantInt>(Idx)) {
  2339. allImmIndex = false;
  2340. break;
  2341. }
  2342. }
  2343. if (allImmIndex) {
  2344. const DataLayout &DL = ValCtx.DL;
  2345. Value *Ptr = GEP->getPointerOperand();
  2346. unsigned size =
  2347. DL.getTypeAllocSize(Ptr->getType()->getPointerElementType());
  2348. unsigned valSize = DL.getTypeAllocSize(GEP->getType()->getPointerElementType());
  2349. SmallVector<Value *, 8> Indices(GEP->idx_begin(), GEP->idx_end());
  2350. unsigned offset =
  2351. DL.getIndexedOffset(GEP->getPointerOperandType(), Indices);
  2352. if ((offset + valSize) > size) {
  2353. ValCtx.EmitInstrError(GEP, ValidationRule::InstrInBoundsAccess);
  2354. }
  2355. }
  2356. } break;
  2357. case Instruction::SDiv: {
  2358. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2359. Value *V = BO->getOperand(1);
  2360. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2361. if (imm->getValue().getLimitedValue() == 0) {
  2362. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoIDivByZero);
  2363. }
  2364. }
  2365. } break;
  2366. case Instruction::UDiv: {
  2367. BinaryOperator *BO = cast<BinaryOperator>(&I);
  2368. Value *V = BO->getOperand(1);
  2369. if (ConstantInt *imm = dyn_cast<ConstantInt>(V)) {
  2370. if (imm->getValue().getLimitedValue() == 0) {
  2371. ValCtx.EmitInstrError(BO, ValidationRule::InstrNoUDivByZero);
  2372. }
  2373. }
  2374. } break;
  2375. case Instruction::AddrSpaceCast: {
  2376. AddrSpaceCastInst *Cast = cast<AddrSpaceCastInst>(&I);
  2377. unsigned ToAddrSpace = Cast->getType()->getPointerAddressSpace();
  2378. unsigned FromAddrSpace = Cast->getOperand(0)->getType()->getPointerAddressSpace();
  2379. if (ToAddrSpace != DXIL::kGenericPointerAddrSpace &&
  2380. FromAddrSpace != DXIL::kGenericPointerAddrSpace) {
  2381. ValCtx.EmitInstrError(Cast, ValidationRule::InstrNoGenericPtrAddrSpaceCast);
  2382. }
  2383. } break;
  2384. case Instruction::BitCast: {
  2385. BitCastInst *Cast = cast<BitCastInst>(&I);
  2386. Type *FromTy = Cast->getOperand(0)->getType();
  2387. Type *ToTy = Cast->getType();
  2388. if (isa<PointerType>(FromTy)) {
  2389. FromTy = FromTy->getPointerElementType();
  2390. ToTy = ToTy->getPointerElementType();
  2391. unsigned FromSize = ValCtx.DL.getTypeAllocSize(FromTy);
  2392. unsigned ToSize = ValCtx.DL.getTypeAllocSize(ToTy);
  2393. if (FromSize != ToSize) {
  2394. ValCtx.EmitInstrError(Cast, ValidationRule::InstrPtrBitCast);
  2395. continue;
  2396. }
  2397. while (isa<ArrayType>(FromTy)) {
  2398. FromTy = FromTy->getArrayElementType();
  2399. }
  2400. while (isa<ArrayType>(ToTy)) {
  2401. ToTy = ToTy->getArrayElementType();
  2402. }
  2403. }
  2404. if (isa<StructType>(FromTy) || isa<StructType>(ToTy)) {
  2405. ValCtx.EmitInstrError(Cast, ValidationRule::InstrStructBitCast);
  2406. continue;
  2407. }
  2408. bool IsMinPrecisionTy =
  2409. (ValCtx.DL.getTypeStoreSize(FromTy) < 4 ||
  2410. ValCtx.DL.getTypeStoreSize(ToTy) < 4) &&
  2411. !ValCtx.DxilMod.m_ShaderFlags.GetUseNativeLowPrecision();
  2412. if (IsMinPrecisionTy) {
  2413. ValCtx.EmitInstrError(Cast, ValidationRule::InstrMinPrecisonBitCast);
  2414. }
  2415. } break;
  2416. }
  2417. if (PointerType *PT = dyn_cast<PointerType>(I.getType())) {
  2418. if (PT->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2419. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  2420. Value *Ptr = GEP->getPointerOperand();
  2421. if (!isa<GlobalVariable>(Ptr)) {
  2422. ValCtx.EmitInstrError(
  2423. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2424. }
  2425. } else if (BitCastInst *BCI = dyn_cast<BitCastInst>(&I)) {
  2426. Value *Ptr = BCI->getOperand(0);
  2427. if (!isa<GetElementPtrInst>(Ptr) && !isa<GlobalVariable>(Ptr)) {
  2428. ValCtx.EmitInstrError(
  2429. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2430. }
  2431. } else {
  2432. ValCtx.EmitInstrError(
  2433. &I, ValidationRule::InstrFailToResloveTGSMPointer);
  2434. }
  2435. }
  2436. }
  2437. }
  2438. ValidateControlFlowHint(*b, ValCtx);
  2439. }
  2440. if (!gradientOps.empty()) {
  2441. ValidateGradientOps(F, gradientOps, barriers, ValCtx);
  2442. }
  2443. }
  2444. static void ValidateFunction(Function &F, ValidationContext &ValCtx) {
  2445. if (F.isDeclaration()) {
  2446. ValidateExternalFunction(&F, ValCtx);
  2447. } else {
  2448. if (!F.arg_empty())
  2449. ValCtx.EmitFormatError(ValidationRule::FlowFunctionCall,
  2450. {F.getName().str()});
  2451. DxilFunctionAnnotation *funcAnnotation =
  2452. ValCtx.DxilMod.GetTypeSystem().GetFunctionAnnotation(&F);
  2453. if (!funcAnnotation) {
  2454. ValCtx.EmitFormatError(ValidationRule::MetaFunctionAnnotation,
  2455. {F.getName().str()});
  2456. return;
  2457. }
  2458. // Validate parameter type.
  2459. for (auto &arg : F.args()) {
  2460. Type *argTy = arg.getType();
  2461. if (argTy->isPointerTy())
  2462. argTy = argTy->getPointerElementType();
  2463. while (argTy->isArrayTy()) {
  2464. argTy = argTy->getArrayElementType();
  2465. }
  2466. if (argTy->isStructTy()) {
  2467. if (arg.hasName())
  2468. ValCtx.EmitFormatError(
  2469. ValidationRule::DeclFnFlattenParam,
  2470. {arg.getName().str(), F.getName().str()});
  2471. else
  2472. ValCtx.EmitFormatError(ValidationRule::DeclFnFlattenParam,
  2473. {std::to_string(arg.getArgNo()),
  2474. F.getName().str()});
  2475. break;
  2476. }
  2477. }
  2478. ValidateFunctionBody(&F, ValCtx);
  2479. }
  2480. ValidateFunctionAttribute(&F, ValCtx);
  2481. if (F.hasMetadata()) {
  2482. ValidateFunctionMetadata(&F, ValCtx);
  2483. }
  2484. }
  2485. static void ValidateGlobalVariable(GlobalVariable &GV,
  2486. ValidationContext &ValCtx) {
  2487. bool isInternalGV =
  2488. dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV);
  2489. if (!isInternalGV) {
  2490. if (!GV.user_empty()) {
  2491. bool hasInstructionUser = false;
  2492. for (User *U : GV.users()) {
  2493. if (isa<Instruction>(U)) {
  2494. hasInstructionUser = true;
  2495. break;
  2496. }
  2497. }
  2498. // External GV should not have instruction user.
  2499. if (hasInstructionUser) {
  2500. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclNotUsedExternal);
  2501. }
  2502. }
  2503. // Must have metadata description for each variable.
  2504. } else {
  2505. // Internal GV must have user.
  2506. if (GV.user_empty()) {
  2507. ValCtx.EmitGlobalValueError(&GV, ValidationRule::DeclUsedInternal);
  2508. }
  2509. // Validate type for internal globals.
  2510. if (dxilutil::IsStaticGlobal(&GV) || dxilutil::IsSharedMemoryGlobal(&GV)) {
  2511. Type *Ty = GV.getType()->getPointerElementType();
  2512. ValidateType(Ty, ValCtx);
  2513. }
  2514. }
  2515. }
  2516. static void CollectFixAddressAccess(Value *V,
  2517. std::vector<StoreInst *> &fixAddrTGSMList) {
  2518. for (User *U : V->users()) {
  2519. if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  2520. if (isa<ConstantExpr>(GEP) || GEP->hasAllConstantIndices()) {
  2521. CollectFixAddressAccess(GEP, fixAddrTGSMList);
  2522. }
  2523. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  2524. fixAddrTGSMList.emplace_back(SI);
  2525. }
  2526. }
  2527. }
  2528. static bool IsDivergent(Value *V) {
  2529. // TODO: return correct result.
  2530. return false;
  2531. }
  2532. static void ValidateTGSMRaceCondition(std::vector<StoreInst *> &fixAddrTGSMList,
  2533. ValidationContext &ValCtx) {
  2534. std::unordered_set<Function *> fixAddrTGSMFuncSet;
  2535. for (StoreInst *I : fixAddrTGSMList) {
  2536. BasicBlock *BB = I->getParent();
  2537. fixAddrTGSMFuncSet.insert(BB->getParent());
  2538. }
  2539. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  2540. if (F.isDeclaration() || !fixAddrTGSMFuncSet.count(&F))
  2541. continue;
  2542. PostDominatorTree PDT;
  2543. PDT.runOnFunction(F);
  2544. BasicBlock *Entry = &F.getEntryBlock();
  2545. for (StoreInst *SI : fixAddrTGSMList) {
  2546. BasicBlock *BB = SI->getParent();
  2547. if (BB->getParent() == &F) {
  2548. if (PDT.dominates(BB, Entry)) {
  2549. if (IsDivergent(SI->getValueOperand()))
  2550. ValCtx.EmitInstrError(SI, ValidationRule::InstrTGSMRaceCond);
  2551. }
  2552. }
  2553. }
  2554. }
  2555. }
  2556. static void ValidateGlobalVariables(ValidationContext &ValCtx) {
  2557. DxilModule &M = ValCtx.DxilMod;
  2558. unsigned TGSMSize = 0;
  2559. std::vector<StoreInst*> fixAddrTGSMList;
  2560. const DataLayout &DL = M.GetModule()->getDataLayout();
  2561. for (GlobalVariable &GV : M.GetModule()->globals()) {
  2562. ValidateGlobalVariable(GV, ValCtx);
  2563. if (GV.getType()->getAddressSpace() == DXIL::kTGSMAddrSpace) {
  2564. TGSMSize += DL.getTypeAllocSize(GV.getType()->getElementType());
  2565. CollectFixAddressAccess(&GV, fixAddrTGSMList);
  2566. }
  2567. }
  2568. if (TGSMSize > DXIL::kMaxTGSMSize) {
  2569. ValCtx.EmitFormatError(ValidationRule::SmMaxTGSMSize,
  2570. {std::to_string(TGSMSize),
  2571. std::to_string(DXIL::kMaxTGSMSize)});
  2572. }
  2573. if (!fixAddrTGSMList.empty()) {
  2574. ValidateTGSMRaceCondition(fixAddrTGSMList, ValCtx);
  2575. }
  2576. }
  2577. static void ValidateValidatorVersion(ValidationContext &ValCtx) {
  2578. Module *pModule = &ValCtx.M;
  2579. NamedMDNode *pNode = pModule->getNamedMetadata("dx.valver");
  2580. if (pNode == nullptr) {
  2581. return;
  2582. }
  2583. if (pNode->getNumOperands() == 1) {
  2584. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  2585. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  2586. uint64_t majorVer, minorVer;
  2587. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  2588. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  2589. unsigned curMajor, curMinor;
  2590. GetValidationVersion(&curMajor, &curMinor);
  2591. // This will need to be updated as major/minor versions evolve,
  2592. // depending on the degree of compat across versions.
  2593. if (majorVer == curMajor && minorVer <= curMinor) {
  2594. return;
  2595. }
  2596. }
  2597. }
  2598. }
  2599. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  2600. }
  2601. static void ValidateDxilVersion(ValidationContext &ValCtx) {
  2602. Module *pModule = &ValCtx.M;
  2603. NamedMDNode *pNode = pModule->getNamedMetadata("dx.version");
  2604. if (pNode && pNode->getNumOperands() == 1) {
  2605. MDTuple *pVerValues = dyn_cast<MDTuple>(pNode->getOperand(0));
  2606. if (pVerValues != nullptr && pVerValues->getNumOperands() == 2) {
  2607. uint64_t majorVer, minorVer;
  2608. if (GetNodeOperandAsInt(ValCtx, pVerValues, 0, &majorVer) &&
  2609. GetNodeOperandAsInt(ValCtx, pVerValues, 1, &minorVer)) {
  2610. // This will need to be updated as dxil major/minor versions evolve,
  2611. // depending on the degree of compat across versions.
  2612. if ((majorVer == 1 && minorVer < 3) &&
  2613. (majorVer == ValCtx.m_DxilMajor && minorVer == ValCtx.m_DxilMinor)) {
  2614. return;
  2615. }
  2616. }
  2617. }
  2618. }
  2619. ValCtx.EmitError(ValidationRule::MetaWellFormed);
  2620. }
  2621. static void ValidateTypeAnnotation(ValidationContext &ValCtx) {
  2622. if (ValCtx.m_DxilMajor == 1 && ValCtx.m_DxilMinor >= 2) {
  2623. Module *pModule = &ValCtx.M;
  2624. NamedMDNode *TA = pModule->getNamedMetadata("dx.typeAnnotations");
  2625. if (TA == nullptr)
  2626. return;
  2627. for (unsigned i = 0, end = TA->getNumOperands(); i < end; ++i) {
  2628. MDTuple *TANode = dyn_cast<MDTuple>(TA->getOperand(i));
  2629. if (TANode->getNumOperands() < 3) {
  2630. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  2631. return;
  2632. }
  2633. ConstantInt *tag = mdconst::extract<ConstantInt>(TANode->getOperand(0));
  2634. uint64_t tagValue = tag->getZExtValue();
  2635. if (tagValue != DxilMDHelper::kDxilTypeSystemStructTag &&
  2636. tagValue != DxilMDHelper::kDxilTypeSystemFunctionTag) {
  2637. ValCtx.EmitMetaError(TANode, ValidationRule::MetaWellFormed);
  2638. return;
  2639. }
  2640. }
  2641. }
  2642. }
  2643. static void ValidateMetadata(ValidationContext &ValCtx) {
  2644. Module *pModule = &ValCtx.M;
  2645. const std::string &target = pModule->getTargetTriple();
  2646. if (target != "dxil-ms-dx") {
  2647. ValCtx.EmitFormatError(ValidationRule::MetaTarget, {target});
  2648. }
  2649. // The llvm.dbg.(cu/contents/defines/mainFileName/arg) named metadata nodes
  2650. // are only available in debug modules, not in the validated ones.
  2651. // llvm.bitsets is also disallowed.
  2652. //
  2653. // These are verified in lib/IR/Verifier.cpp.
  2654. StringMap<bool> llvmNamedMeta;
  2655. llvmNamedMeta["llvm.ident"];
  2656. llvmNamedMeta["llvm.module.flags"];
  2657. for (auto &NamedMetaNode : pModule->named_metadata()) {
  2658. if (!DxilModule::IsKnownNamedMetaData(NamedMetaNode)) {
  2659. StringRef name = NamedMetaNode.getName();
  2660. if (!name.startswith_lower("llvm."))
  2661. ValCtx.EmitFormatError(ValidationRule::MetaKnown, {name.str()});
  2662. else {
  2663. if (llvmNamedMeta.count(name) == 0) {
  2664. ValCtx.EmitFormatError(ValidationRule::MetaKnown,
  2665. {name.str()});
  2666. }
  2667. }
  2668. }
  2669. }
  2670. const hlsl::ShaderModel *SM = ValCtx.DxilMod.GetShaderModel();
  2671. if (!SM->IsValidForDxil()) {
  2672. ValCtx.EmitFormatError(ValidationRule::SmName,
  2673. {ValCtx.DxilMod.GetShaderModel()->GetName()});
  2674. }
  2675. if (SM->GetMajor() == 6) {
  2676. // Make sure DxilVersion matches the shader model.
  2677. unsigned SMDxilMajor, SMDxilMinor;
  2678. SM->GetDxilVersion(SMDxilMajor, SMDxilMinor);
  2679. if (ValCtx.m_DxilMajor != SMDxilMajor || ValCtx.m_DxilMinor != SMDxilMinor) {
  2680. ValCtx.EmitFormatError(ValidationRule::SmDxilVersion,
  2681. {std::to_string(SMDxilMajor),
  2682. std::to_string(SMDxilMinor)});
  2683. }
  2684. }
  2685. ValidateDxilVersion(ValCtx);
  2686. ValidateValidatorVersion(ValCtx);
  2687. ValidateTypeAnnotation(ValCtx);
  2688. }
  2689. static void ValidateResourceOverlap(
  2690. hlsl::DxilResourceBase &res,
  2691. SpacesAllocator<unsigned, DxilResourceBase> &spaceAllocator,
  2692. ValidationContext &ValCtx) {
  2693. unsigned base = res.GetLowerBound();
  2694. unsigned size = res.GetRangeSize();
  2695. unsigned space = res.GetSpaceID();
  2696. auto &allocator = spaceAllocator.Get(space);
  2697. unsigned end = base + size - 1;
  2698. // unbounded
  2699. if (end < base)
  2700. end = size;
  2701. const DxilResourceBase *conflictRes = allocator.Insert(&res, base, end);
  2702. if (conflictRes) {
  2703. ValCtx.EmitFormatError(
  2704. ValidationRule::SmResourceRangeOverlap,
  2705. {res.GetGlobalName(), std::to_string(base),
  2706. std::to_string(size),
  2707. std::to_string(conflictRes->GetLowerBound()),
  2708. std::to_string(conflictRes->GetRangeSize()),
  2709. std::to_string(space)});
  2710. }
  2711. }
  2712. static void ValidateResource(hlsl::DxilResource &res,
  2713. ValidationContext &ValCtx) {
  2714. switch (res.GetKind()) {
  2715. case DXIL::ResourceKind::RawBuffer:
  2716. case DXIL::ResourceKind::TypedBuffer:
  2717. case DXIL::ResourceKind::TBuffer:
  2718. case DXIL::ResourceKind::StructuredBuffer:
  2719. case DXIL::ResourceKind::Texture1D:
  2720. case DXIL::ResourceKind::Texture1DArray:
  2721. case DXIL::ResourceKind::Texture2D:
  2722. case DXIL::ResourceKind::Texture2DArray:
  2723. case DXIL::ResourceKind::Texture3D:
  2724. case DXIL::ResourceKind::TextureCube:
  2725. case DXIL::ResourceKind::TextureCubeArray:
  2726. if (res.GetSampleCount() > 0) {
  2727. ValCtx.EmitResourceError(&res, ValidationRule::SmSampleCountOnlyOn2DMS);
  2728. }
  2729. break;
  2730. case DXIL::ResourceKind::Texture2DMS:
  2731. case DXIL::ResourceKind::Texture2DMSArray:
  2732. break;
  2733. default:
  2734. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceKind);
  2735. break;
  2736. }
  2737. switch (res.GetCompType().GetKind()) {
  2738. case DXIL::ComponentType::F32:
  2739. case DXIL::ComponentType::SNormF32:
  2740. case DXIL::ComponentType::UNormF32:
  2741. case DXIL::ComponentType::F64:
  2742. case DXIL::ComponentType::I32:
  2743. case DXIL::ComponentType::I64:
  2744. case DXIL::ComponentType::U32:
  2745. case DXIL::ComponentType::U64:
  2746. case DXIL::ComponentType::F16:
  2747. case DXIL::ComponentType::I16:
  2748. case DXIL::ComponentType::U16:
  2749. break;
  2750. default:
  2751. if (!res.IsStructuredBuffer() && !res.IsRawBuffer())
  2752. ValCtx.EmitResourceError(&res, ValidationRule::SmInvalidResourceCompType);
  2753. break;
  2754. }
  2755. if (res.IsStructuredBuffer()) {
  2756. unsigned stride = res.GetElementStride();
  2757. bool alignedTo4Bytes = (stride & 3) == 0;
  2758. if (!alignedTo4Bytes && !ValCtx.M.GetDxilModule().m_ShaderFlags.GetUseNativeLowPrecision()) {
  2759. ValCtx.EmitResourceFormatError(
  2760. &res, ValidationRule::MetaStructBufAlignment,
  2761. {std::to_string(4), std::to_string(stride)});
  2762. }
  2763. if (stride > DXIL::kMaxStructBufferStride) {
  2764. ValCtx.EmitResourceFormatError(
  2765. &res, ValidationRule::MetaStructBufAlignmentOutOfBound,
  2766. {std::to_string(DXIL::kMaxStructBufferStride),
  2767. std::to_string(stride)});
  2768. }
  2769. }
  2770. if (res.IsAnyTexture() || res.IsTypedBuffer()) {
  2771. Type *RetTy = res.GetRetType();
  2772. unsigned size = ValCtx.DxilMod.GetModule()->getDataLayout().getTypeAllocSize(RetTy);
  2773. if (size > 4*4) {
  2774. ValCtx.EmitResourceError(&res, ValidationRule::MetaTextureType);
  2775. }
  2776. }
  2777. }
  2778. static void
  2779. CollectCBufferRanges(DxilStructAnnotation *annotation,
  2780. SpanAllocator<unsigned, DxilFieldAnnotation> &constAllocator,
  2781. unsigned base, DxilTypeSystem &typeSys, StringRef cbName,
  2782. ValidationContext &ValCtx) {
  2783. unsigned cbSize = annotation->GetCBufferSize();
  2784. const StructType *ST = annotation->GetStructType();
  2785. for (int i = annotation->GetNumFields() - 1; i >= 0; i--) {
  2786. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  2787. Type *EltTy = ST->getElementType(i);
  2788. unsigned offset = fieldAnnotation.GetCBufferOffset();
  2789. unsigned EltSize = dxilutil::GetLegacyCBufferFieldElementSize(
  2790. fieldAnnotation, EltTy, typeSys);
  2791. bool bOutOfBound = false;
  2792. if (!EltTy->isAggregateType()) {
  2793. bOutOfBound = (offset + EltSize) > cbSize;
  2794. if (!bOutOfBound) {
  2795. if (constAllocator.Insert(&fieldAnnotation, base + offset,
  2796. base + offset + EltSize - 1)) {
  2797. ValCtx.EmitFormatError(
  2798. ValidationRule::SmCBufferOffsetOverlap,
  2799. {cbName, std::to_string(base + offset)});
  2800. }
  2801. }
  2802. } else if (isa<ArrayType>(EltTy)) {
  2803. unsigned arrayCount = 1;
  2804. while (isa<ArrayType>(EltTy)) {
  2805. arrayCount *= EltTy->getArrayNumElements();
  2806. EltTy = EltTy->getArrayElementType();
  2807. }
  2808. unsigned arrayBase = base + offset;
  2809. DxilStructAnnotation *EltAnnotation = nullptr;
  2810. if (StructType *EltST = dyn_cast<StructType>(EltTy))
  2811. EltAnnotation = typeSys.GetStructAnnotation(EltST);
  2812. for (unsigned idx = 0; idx < arrayCount; idx++) {
  2813. // 16 bytes align except last component.
  2814. if (idx < (arrayCount - 1)) {
  2815. arrayBase = (arrayBase + 15) & ~(0xf);
  2816. }
  2817. if (arrayBase > (base + cbSize)) {
  2818. bOutOfBound = true;
  2819. break;
  2820. }
  2821. if (!EltAnnotation) {
  2822. if (constAllocator.Insert(&fieldAnnotation, arrayBase,
  2823. arrayBase + EltSize - 1)) {
  2824. ValCtx.EmitFormatError(
  2825. ValidationRule::SmCBufferOffsetOverlap,
  2826. {cbName, std::to_string(base + offset)});
  2827. }
  2828. } else {
  2829. CollectCBufferRanges(EltAnnotation,
  2830. constAllocator, arrayBase, typeSys,
  2831. cbName, ValCtx);
  2832. }
  2833. arrayBase += EltSize;
  2834. }
  2835. } else {
  2836. cast<StructType>(EltTy);
  2837. bOutOfBound = (offset + EltSize) > cbSize;
  2838. }
  2839. if (bOutOfBound) {
  2840. ValCtx.EmitFormatError(ValidationRule::SmCBufferElementOverflow,
  2841. {cbName, std::to_string(base + offset)});
  2842. }
  2843. }
  2844. }
  2845. static void ValidateCBuffer(DxilCBuffer &cb, ValidationContext &ValCtx) {
  2846. Type *Ty = cb.GetGlobalSymbol()->getType()->getPointerElementType();
  2847. if (cb.GetRangeSize() != 1) {
  2848. Ty = Ty->getArrayElementType();
  2849. }
  2850. if (!isa<StructType>(Ty)) {
  2851. ValCtx.EmitResourceError(&cb,
  2852. ValidationRule::SmCBufferTemplateTypeMustBeStruct);
  2853. return;
  2854. }
  2855. StructType *ST = cast<StructType>(Ty);
  2856. DxilTypeSystem &typeSys = ValCtx.DxilMod.GetTypeSystem();
  2857. DxilStructAnnotation *annotation = typeSys.GetStructAnnotation(ST);
  2858. if (!annotation)
  2859. return;
  2860. // Collect constant ranges.
  2861. std::vector<std::pair<unsigned, unsigned>> constRanges;
  2862. SpanAllocator<unsigned, DxilFieldAnnotation> constAllocator(0,
  2863. // 4096 * 16 bytes.
  2864. DXIL::kMaxCBufferSize << 4);
  2865. CollectCBufferRanges(annotation, constAllocator,
  2866. 0, typeSys,
  2867. cb.GetGlobalName(), ValCtx);
  2868. }
  2869. static void ValidateResources(ValidationContext &ValCtx) {
  2870. const vector<unique_ptr<DxilResource>> &uavs = ValCtx.DxilMod.GetUAVs();
  2871. bool hasROV = false;
  2872. SpacesAllocator<unsigned, DxilResourceBase> uavAllocator;
  2873. for (auto &uav : uavs) {
  2874. if (uav->IsROV()) {
  2875. hasROV = true;
  2876. if (!ValCtx.DxilMod.GetShaderModel()->IsPS()) {
  2877. ValCtx.EmitResourceError(uav.get(), ValidationRule::SmROVOnlyInPS);
  2878. }
  2879. }
  2880. switch (uav->GetKind()) {
  2881. case DXIL::ResourceKind::Texture2DMS:
  2882. case DXIL::ResourceKind::Texture2DMSArray:
  2883. case DXIL::ResourceKind::TextureCube:
  2884. case DXIL::ResourceKind::TextureCubeArray:
  2885. ValCtx.EmitResourceError(uav.get(),
  2886. ValidationRule::SmInvalidTextureKindOnUAV);
  2887. break;
  2888. default:
  2889. break;
  2890. }
  2891. if (uav->HasCounter() && !uav->IsStructuredBuffer()) {
  2892. ValCtx.EmitResourceError(uav.get(),
  2893. ValidationRule::SmCounterOnlyOnStructBuf);
  2894. }
  2895. if (uav->HasCounter() && uav->IsGloballyCoherent())
  2896. ValCtx.EmitResourceError(uav.get(),
  2897. ValidationRule::MetaGlcNotOnAppendConsume);
  2898. ValidateResource(*uav, ValCtx);
  2899. ValidateResourceOverlap(*uav, uavAllocator, ValCtx);
  2900. }
  2901. SpacesAllocator<unsigned, DxilResourceBase> srvAllocator;
  2902. const vector<unique_ptr<DxilResource>> &srvs = ValCtx.DxilMod.GetSRVs();
  2903. for (auto &srv : srvs) {
  2904. ValidateResource(*srv, ValCtx);
  2905. ValidateResourceOverlap(*srv, srvAllocator, ValCtx);
  2906. }
  2907. hlsl::DxilResourceBase *pNonDense;
  2908. if (!AreDxilResourcesDense(&ValCtx.M, &pNonDense)) {
  2909. ValCtx.EmitResourceError(pNonDense, ValidationRule::MetaDenseResIDs);
  2910. }
  2911. SpacesAllocator<unsigned, DxilResourceBase> samplerAllocator;
  2912. for (auto &sampler : ValCtx.DxilMod.GetSamplers()) {
  2913. if (sampler->GetSamplerKind() == DXIL::SamplerKind::Invalid) {
  2914. ValCtx.EmitResourceError(sampler.get(),
  2915. ValidationRule::MetaValidSamplerMode);
  2916. }
  2917. ValidateResourceOverlap(*sampler, samplerAllocator, ValCtx);
  2918. }
  2919. SpacesAllocator<unsigned, DxilResourceBase> cbufferAllocator;
  2920. for (auto &cbuffer : ValCtx.DxilMod.GetCBuffers()) {
  2921. ValidateCBuffer(*cbuffer, ValCtx);
  2922. ValidateResourceOverlap(*cbuffer, cbufferAllocator, ValCtx);
  2923. }
  2924. }
  2925. static void ValidateShaderFlags(ValidationContext &ValCtx) {
  2926. DxilModule::ShaderFlags calcFlags;
  2927. ValCtx.DxilMod.CollectShaderFlags(calcFlags);
  2928. const uint64_t mask = DxilModule::ShaderFlags::GetShaderFlagsRawForCollection();
  2929. uint64_t declaredFlagsRaw = ValCtx.DxilMod.m_ShaderFlags.GetShaderFlagsRaw();
  2930. uint64_t calcFlagsRaw = calcFlags.GetShaderFlagsRaw();
  2931. declaredFlagsRaw &= mask;
  2932. calcFlagsRaw &= mask;
  2933. if (declaredFlagsRaw == calcFlagsRaw) {
  2934. return;
  2935. }
  2936. ValCtx.EmitError(ValidationRule::MetaFlagsUsage);
  2937. ValCtx.DiagStream() << "Flags declared=" << declaredFlagsRaw
  2938. << ", actual=" << calcFlagsRaw << "\n";
  2939. }
  2940. static void ValidateSignatureElement(DxilSignatureElement &SE,
  2941. ValidationContext &ValCtx) {
  2942. DXIL::SemanticKind semanticKind = SE.GetSemantic()->GetKind();
  2943. CompType::Kind compKind = SE.GetCompType().GetKind();
  2944. DXIL::InterpolationMode Mode = SE.GetInterpolationMode()->GetKind();
  2945. StringRef Name = SE.GetName();
  2946. if (Name.size() < 1 || Name.size() > 64) {
  2947. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemanticLen);
  2948. }
  2949. if (semanticKind > DXIL::SemanticKind::Arbitrary && semanticKind < DXIL::SemanticKind::Invalid) {
  2950. if (semanticKind != Semantic::GetByName(SE.GetName())->GetKind()) {
  2951. ValCtx.EmitFormatError(ValidationRule::MetaSemaKindMatchesName,
  2952. {SE.GetName(), SE.GetSemantic()->GetName()});
  2953. }
  2954. }
  2955. unsigned compWidth = 0;
  2956. bool compFloat = false;
  2957. bool compInt = false;
  2958. bool compUnsigned = false;
  2959. bool compBool = false;
  2960. bool compSNorm = false;
  2961. bool compUNorm = false;
  2962. switch (compKind) {
  2963. case CompType::Kind::U64: compWidth = 64; compInt = true; compUnsigned = true; break;
  2964. case CompType::Kind::I64: compWidth = 64; compInt = true; break;
  2965. case CompType::Kind::U32: compWidth = 32; compInt = true; compUnsigned = true; break;
  2966. case CompType::Kind::I32: compWidth = 32; compInt = true; break;
  2967. case CompType::Kind::U16: compWidth = 16; compInt = true; compUnsigned = true; break;
  2968. case CompType::Kind::I16: compWidth = 16; compInt = true; break;
  2969. case CompType::Kind::I1: compWidth = 1; compBool = true; break;
  2970. case CompType::Kind::F64: compWidth = 64; compFloat = true; break;
  2971. case CompType::Kind::F32: compWidth = 32; compFloat = true; break;
  2972. case CompType::Kind::F16: compWidth = 16; compFloat = true; break;
  2973. case CompType::Kind::SNormF64: compWidth = 64; compFloat = true; compSNorm = true; break;
  2974. case CompType::Kind::SNormF32: compWidth = 32; compFloat = true; compSNorm = true; break;
  2975. case CompType::Kind::SNormF16: compWidth = 16; compFloat = true; compSNorm = true; break;
  2976. case CompType::Kind::UNormF64: compWidth = 64; compFloat = true; compUNorm = true; break;
  2977. case CompType::Kind::UNormF32: compWidth = 32; compFloat = true; compUNorm = true; break;
  2978. case CompType::Kind::UNormF16: compWidth = 16; compFloat = true; compUNorm = true; break;
  2979. case CompType::Kind::Invalid:
  2980. default:
  2981. ValCtx.EmitFormatError(ValidationRule::MetaSignatureCompType, { SE.GetName() });
  2982. break;
  2983. }
  2984. if (compInt || compBool) {
  2985. switch (Mode) {
  2986. case DXIL::InterpolationMode::Linear:
  2987. case DXIL::InterpolationMode::LinearCentroid:
  2988. case DXIL::InterpolationMode::LinearNoperspective:
  2989. case DXIL::InterpolationMode::LinearNoperspectiveCentroid:
  2990. case DXIL::InterpolationMode::LinearSample:
  2991. case DXIL::InterpolationMode::LinearNoperspectiveSample: {
  2992. ValCtx.EmitFormatError(ValidationRule::MetaIntegerInterpMode, {SE.GetName()});
  2993. } break;
  2994. default:
  2995. break;
  2996. }
  2997. }
  2998. // Elements that should not appear in the Dxil signature:
  2999. bool bAllowedInSig = true;
  3000. bool bShouldBeAllocated = true;
  3001. switch (SE.GetInterpretation()) {
  3002. case DXIL::SemanticInterpretationKind::NA:
  3003. case DXIL::SemanticInterpretationKind::NotInSig:
  3004. case DXIL::SemanticInterpretationKind::Invalid:
  3005. bAllowedInSig = false;
  3006. __fallthrough;
  3007. case DXIL::SemanticInterpretationKind::NotPacked:
  3008. case DXIL::SemanticInterpretationKind::Shadow:
  3009. bShouldBeAllocated = false;
  3010. break;
  3011. default:
  3012. break;
  3013. }
  3014. const char *inputOutput = nullptr;
  3015. if (SE.IsInput())
  3016. inputOutput = "Input";
  3017. else if (SE.IsOutput())
  3018. inputOutput = "Output";
  3019. else
  3020. inputOutput = "PatchConstant";
  3021. if (!bAllowedInSig) {
  3022. ValCtx.EmitFormatError(
  3023. ValidationRule::SmSemantic,
  3024. {SE.GetName(), ValCtx.DxilMod.GetShaderModel()->GetKindName(), inputOutput});
  3025. } else if (bShouldBeAllocated && !SE.IsAllocated()) {
  3026. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldBeAllocated,
  3027. {inputOutput, SE.GetName()});
  3028. } else if (!bShouldBeAllocated && SE.IsAllocated()) {
  3029. ValCtx.EmitFormatError(ValidationRule::MetaSemanticShouldNotBeAllocated,
  3030. {inputOutput, SE.GetName()});
  3031. }
  3032. bool bIsClipCull = false;
  3033. bool bIsTessfactor = false;
  3034. bool bIsBarycentric = false;
  3035. switch (semanticKind) {
  3036. case DXIL::SemanticKind::Depth:
  3037. case DXIL::SemanticKind::DepthGreaterEqual:
  3038. case DXIL::SemanticKind::DepthLessEqual:
  3039. if (!compFloat || compWidth > 32 || SE.GetCols() != 1) {
  3040. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3041. {SE.GetSemantic()->GetName(), "float"});
  3042. }
  3043. break;
  3044. case DXIL::SemanticKind::Coverage:
  3045. DXASSERT(!SE.IsInput() || !bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  3046. __fallthrough;
  3047. case DXIL::SemanticKind::InnerCoverage:
  3048. case DXIL::SemanticKind::OutputControlPointID:
  3049. if (compKind != CompType::Kind::U32 || SE.GetCols() != 1) {
  3050. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3051. {SE.GetSemantic()->GetName(), "uint"});
  3052. }
  3053. break;
  3054. case DXIL::SemanticKind::Position:
  3055. if (!compFloat || compWidth > 32 || SE.GetCols() != 4) {
  3056. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3057. {SE.GetSemantic()->GetName(), "float4"});
  3058. }
  3059. break;
  3060. case DXIL::SemanticKind::Target:
  3061. if (compWidth > 32) {
  3062. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3063. {SE.GetSemantic()->GetName(), "float/int/uint"});
  3064. }
  3065. break;
  3066. case DXIL::SemanticKind::ClipDistance:
  3067. case DXIL::SemanticKind::CullDistance:
  3068. bIsClipCull = true;
  3069. if (!compFloat || compWidth > 32) {
  3070. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3071. {SE.GetSemantic()->GetName(), "float"});
  3072. }
  3073. // NOTE: clip cull distance size is checked at ValidateSignature.
  3074. break;
  3075. case DXIL::SemanticKind::IsFrontFace:
  3076. if (!compBool || SE.GetCols() != 1) {
  3077. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3078. {SE.GetSemantic()->GetName(), "bool"});
  3079. }
  3080. break;
  3081. case DXIL::SemanticKind::RenderTargetArrayIndex:
  3082. case DXIL::SemanticKind::ViewPortArrayIndex:
  3083. case DXIL::SemanticKind::VertexID:
  3084. case DXIL::SemanticKind::PrimitiveID:
  3085. case DXIL::SemanticKind::InstanceID:
  3086. case DXIL::SemanticKind::GSInstanceID:
  3087. case DXIL::SemanticKind::SampleIndex:
  3088. case DXIL::SemanticKind::StencilRef:
  3089. if ((compKind != CompType::Kind::U32 && compKind != CompType::Kind::U16) || SE.GetCols() != 1) {
  3090. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3091. {SE.GetSemantic()->GetName(), "uint"});
  3092. }
  3093. break;
  3094. case DXIL::SemanticKind::TessFactor:
  3095. case DXIL::SemanticKind::InsideTessFactor:
  3096. // NOTE: the size check is at CheckPatchConstantSemantic.
  3097. bIsTessfactor = true;
  3098. if (!compFloat || compWidth > 32) {
  3099. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType,
  3100. {SE.GetSemantic()->GetName(), "float"});
  3101. }
  3102. break;
  3103. case DXIL::SemanticKind::Arbitrary:
  3104. break;
  3105. case DXIL::SemanticKind::DomainLocation:
  3106. case DXIL::SemanticKind::Invalid:
  3107. DXASSERT(!bAllowedInSig, "else internal inconsistency between semantic interpretation table and validation code");
  3108. break;
  3109. case DXIL::SemanticKind::Barycentrics:
  3110. bIsBarycentric = true;
  3111. if (!compFloat || compWidth > 32) {
  3112. ValCtx.EmitFormatError(ValidationRule::MetaSemanticCompType, {SE.GetSemantic()->GetName(), "float"});
  3113. }
  3114. if (Mode != InterpolationMode::Kind::Linear &&
  3115. Mode != InterpolationMode::Kind::LinearCentroid &&
  3116. Mode != InterpolationMode::Kind::LinearNoperspective &&
  3117. Mode != InterpolationMode::Kind::LinearNoperspectiveCentroid &&
  3118. Mode != InterpolationMode::Kind::LinearNoperspectiveSample &&
  3119. Mode != InterpolationMode::Kind::LinearSample) {
  3120. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsInterpolation);
  3121. }
  3122. if (SE.GetCols() != 3) {
  3123. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaBarycentricsFloat3);
  3124. }
  3125. break;
  3126. default:
  3127. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSemaKindValid);
  3128. break;
  3129. }
  3130. if (ValCtx.DxilMod.GetShaderModel()->IsGS() && SE.IsOutput()) {
  3131. if (SE.GetOutputStream() >= DXIL::kNumOutputStreams) {
  3132. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  3133. {std::to_string(SE.GetOutputStream()),
  3134. std::to_string(DXIL::kNumOutputStreams - 1)});
  3135. }
  3136. } else {
  3137. if (SE.GetOutputStream() > 0) {
  3138. ValCtx.EmitFormatError(ValidationRule::SmStreamIndexRange,
  3139. {std::to_string(SE.GetOutputStream()),
  3140. "0"});
  3141. }
  3142. }
  3143. if (ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  3144. if (SE.GetOutputStream() != 0) {
  3145. if (ValCtx.DxilMod.GetStreamPrimitiveTopology() !=
  3146. DXIL::PrimitiveTopology::PointList) {
  3147. ValCtx.EmitSignatureError(&SE,
  3148. ValidationRule::SmMultiStreamMustBePoint);
  3149. }
  3150. }
  3151. }
  3152. if (semanticKind == DXIL::SemanticKind::Target) {
  3153. // Verify packed row == semantic index
  3154. unsigned row = SE.GetStartRow();
  3155. for (unsigned i : SE.GetSemanticIndexVec()) {
  3156. if (row != i) {
  3157. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetIndexMatchesRow);
  3158. }
  3159. ++row;
  3160. }
  3161. // Verify packed col is 0
  3162. if (SE.GetStartCol() != 0) {
  3163. ValCtx.EmitSignatureError(&SE, ValidationRule::SmPSTargetCol0);
  3164. }
  3165. // Verify max row used < 8
  3166. if (SE.GetStartRow() + SE.GetRows() > 8) {
  3167. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {"SV_Target", "7"});
  3168. }
  3169. } else if (bAllowedInSig && semanticKind != DXIL::SemanticKind::Arbitrary) {
  3170. if (bIsBarycentric) {
  3171. if (SE.GetSemanticStartIndex() > 1) {
  3172. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, { SE.GetSemantic()->GetName(), "1" });
  3173. }
  3174. }
  3175. else if (!bIsClipCull && SE.GetSemanticStartIndex() > 0) {
  3176. ValCtx.EmitFormatError(ValidationRule::MetaSemanticIndexMax, {SE.GetSemantic()->GetName(), "0"});
  3177. }
  3178. // Maximum rows is 1 for system values other than Target
  3179. // with the exception of tessfactors, which are validated in CheckPatchConstantSemantic
  3180. if (!bIsTessfactor && SE.GetRows() > 1) {
  3181. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaSystemValueRows);
  3182. }
  3183. }
  3184. if (SE.GetCols() + (SE.IsAllocated() ? SE.GetStartCol() : 0) > 4) {
  3185. unsigned size = (SE.GetRows() - 1) * 4 + SE.GetCols();
  3186. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  3187. {SE.GetName(),
  3188. std::to_string(SE.GetStartRow()),
  3189. std::to_string(SE.GetStartCol()),
  3190. std::to_string(size)});
  3191. }
  3192. if (!SE.GetInterpolationMode()->IsValid()) {
  3193. ValCtx.EmitSignatureError(&SE, ValidationRule::MetaInterpModeValid);
  3194. }
  3195. }
  3196. static void ValidateSignatureOverlap(
  3197. DxilSignatureElement &E, unsigned maxScalars,
  3198. DxilSignatureAllocator &allocator,
  3199. ValidationContext &ValCtx) {
  3200. // Skip entries that are not or should not be allocated. Validation occurs in ValidateSignatureElement.
  3201. if (!E.IsAllocated())
  3202. return;
  3203. switch (E.GetInterpretation()) {
  3204. case DXIL::SemanticInterpretationKind::NA:
  3205. case DXIL::SemanticInterpretationKind::NotInSig:
  3206. case DXIL::SemanticInterpretationKind::Invalid:
  3207. case DXIL::SemanticInterpretationKind::NotPacked:
  3208. case DXIL::SemanticInterpretationKind::Shadow:
  3209. return;
  3210. default:
  3211. break;
  3212. }
  3213. DxilPackElement PE(&E, allocator.UseMinPrecision());
  3214. DxilSignatureAllocator::ConflictType conflict = allocator.DetectRowConflict(&PE, E.GetStartRow());
  3215. if (conflict == DxilSignatureAllocator::kNoConflict || conflict == DxilSignatureAllocator::kInsufficientFreeComponents)
  3216. conflict = allocator.DetectColConflict(&PE, E.GetStartRow(), E.GetStartCol());
  3217. switch (conflict) {
  3218. case DxilSignatureAllocator::kNoConflict:
  3219. allocator.PlaceElement(&PE, E.GetStartRow(), E.GetStartCol());
  3220. break;
  3221. case DxilSignatureAllocator::kConflictsWithIndexed:
  3222. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  3223. {E.GetName(),
  3224. std::to_string(E.GetStartRow()),
  3225. std::to_string(E.GetStartCol()),
  3226. std::to_string(E.GetRows()),
  3227. std::to_string(E.GetCols())});
  3228. break;
  3229. case DxilSignatureAllocator::kConflictsWithIndexedTessFactor:
  3230. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIndexConflict,
  3231. {E.GetName(),
  3232. std::to_string(E.GetStartRow()),
  3233. std::to_string(E.GetStartCol()),
  3234. std::to_string(E.GetRows()),
  3235. std::to_string(E.GetCols())});
  3236. break;
  3237. case DxilSignatureAllocator::kConflictsWithInterpolationMode:
  3238. ValCtx.EmitFormatError(ValidationRule::MetaInterpModeInOneRow,
  3239. {E.GetName(),
  3240. std::to_string(E.GetStartRow()),
  3241. std::to_string(E.GetStartCol()),
  3242. std::to_string(E.GetRows()),
  3243. std::to_string(E.GetCols())});
  3244. break;
  3245. case DxilSignatureAllocator::kInsufficientFreeComponents:
  3246. DXASSERT(false, "otherwise, conflict not translated");
  3247. break;
  3248. case DxilSignatureAllocator::kOverlapElement:
  3249. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOverlap,
  3250. {E.GetName(),
  3251. std::to_string(E.GetStartRow()),
  3252. std::to_string(E.GetStartCol()),
  3253. std::to_string(E.GetRows()),
  3254. std::to_string(E.GetCols())});
  3255. break;
  3256. case DxilSignatureAllocator::kIllegalComponentOrder:
  3257. ValCtx.EmitFormatError(ValidationRule::MetaSignatureIllegalComponentOrder,
  3258. {E.GetName(),
  3259. std::to_string(E.GetStartRow()),
  3260. std::to_string(E.GetStartCol()),
  3261. std::to_string(E.GetRows()),
  3262. std::to_string(E.GetCols())});
  3263. break;
  3264. case DxilSignatureAllocator::kConflictFit:
  3265. ValCtx.EmitFormatError(ValidationRule::MetaSignatureOutOfRange,
  3266. {E.GetName(),
  3267. std::to_string(E.GetStartRow()),
  3268. std::to_string(E.GetStartCol()),
  3269. std::to_string(E.GetRows()),
  3270. std::to_string(E.GetCols())});
  3271. break;
  3272. case DxilSignatureAllocator::kConflictDataWidth:
  3273. ValCtx.EmitFormatError(ValidationRule::MetaSignatureDataWidth,
  3274. {E.GetName(),
  3275. std::to_string(E.GetStartRow()),
  3276. std::to_string(E.GetStartCol()),
  3277. std::to_string(E.GetRows()),
  3278. std::to_string(E.GetCols())});
  3279. break;
  3280. default:
  3281. DXASSERT(false, "otherwise, unrecognized conflict type from DxilSignatureAllocator");
  3282. }
  3283. }
  3284. static void ValidateSignature(ValidationContext &ValCtx, const DxilSignature &S,
  3285. unsigned maxScalars) {
  3286. DxilSignatureAllocator allocator[DXIL::kNumOutputStreams] = {
  3287. {32, !ValCtx.DxilMod.m_ShaderFlags.GetUseNativeLowPrecision()},
  3288. {32, !ValCtx.DxilMod.m_ShaderFlags.GetUseNativeLowPrecision()},
  3289. {32, !ValCtx.DxilMod.m_ShaderFlags.GetUseNativeLowPrecision()},
  3290. {32, !ValCtx.DxilMod.m_ShaderFlags.GetUseNativeLowPrecision()}};
  3291. unordered_set<Semantic::Kind> semanticUsageSet[DXIL::kNumOutputStreams];
  3292. StringMap<unordered_set<unsigned>> semanticIndexMap[DXIL::kNumOutputStreams];
  3293. unordered_set<unsigned> clipcullRowSet[DXIL::kNumOutputStreams];
  3294. unsigned clipcullComponents[DXIL::kNumOutputStreams] = {0, 0, 0, 0};
  3295. bool isOutput = S.IsOutput();
  3296. unsigned TargetMask = 0;
  3297. DXIL::SemanticKind DepthKind = DXIL::SemanticKind::Invalid;
  3298. const InterpolationMode *prevBaryInterpMode = nullptr;
  3299. unsigned numBarycentrics = 0;
  3300. for (auto &E : S.GetElements()) {
  3301. DXIL::SemanticKind semanticKind = E->GetSemantic()->GetKind();
  3302. ValidateSignatureElement(*E, ValCtx);
  3303. // Avoid OOB indexing on streamId.
  3304. unsigned streamId = E->GetOutputStream();
  3305. if (streamId >= DXIL::kNumOutputStreams ||
  3306. !isOutput ||
  3307. !ValCtx.DxilMod.GetShaderModel()->IsGS()) {
  3308. streamId = 0;
  3309. }
  3310. // Semantic index overlap check, keyed by name.
  3311. std::string nameUpper(E->GetName());
  3312. std::transform(nameUpper.begin(), nameUpper.end(), nameUpper.begin(), toupper);
  3313. unordered_set<unsigned> &semIdxSet = semanticIndexMap[streamId][nameUpper];
  3314. for (unsigned semIdx : E->GetSemanticIndexVec()) {
  3315. if (semIdxSet.count(semIdx) > 0) {
  3316. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3317. {E->GetName(), std::to_string(semIdx)});
  3318. return;
  3319. } else
  3320. semIdxSet.insert(semIdx);
  3321. }
  3322. // SV_Target has special rules
  3323. if (semanticKind == DXIL::SemanticKind::Target) {
  3324. // Validate target overlap
  3325. if (E->GetStartRow() + E->GetRows() <= 8) {
  3326. unsigned mask = ((1 << E->GetRows()) - 1) << E->GetStartRow();
  3327. if (TargetMask & mask) {
  3328. ValCtx.EmitFormatError(ValidationRule::MetaNoSemanticOverlap,
  3329. {"SV_Target", std::to_string(E->GetStartRow())});
  3330. }
  3331. TargetMask = TargetMask | mask;
  3332. }
  3333. if (E->GetRows() > 1) {
  3334. ValCtx.EmitError(ValidationRule::SmNoPSOutputIdx);
  3335. }
  3336. continue;
  3337. }
  3338. if (E->GetSemantic()->IsInvalid())
  3339. continue;
  3340. // validate system value semantic rules
  3341. switch (semanticKind) {
  3342. case DXIL::SemanticKind::Arbitrary:
  3343. break;
  3344. case DXIL::SemanticKind::ClipDistance:
  3345. case DXIL::SemanticKind::CullDistance:
  3346. // Validate max 8 components across 2 rows (registers)
  3347. clipcullRowSet[streamId].insert(E->GetStartRow());
  3348. if (clipcullRowSet[streamId].size() > 2) {
  3349. ValCtx.EmitError(ValidationRule::MetaClipCullMaxRows);
  3350. }
  3351. clipcullComponents[streamId] += E->GetCols();
  3352. if (clipcullComponents[streamId] > 8) {
  3353. ValCtx.EmitError(ValidationRule::MetaClipCullMaxComponents);
  3354. }
  3355. break;
  3356. case DXIL::SemanticKind::Depth:
  3357. case DXIL::SemanticKind::DepthGreaterEqual:
  3358. case DXIL::SemanticKind::DepthLessEqual:
  3359. if (DepthKind != DXIL::SemanticKind::Invalid) {
  3360. ValCtx.EmitError(ValidationRule::SmPSMultipleDepthSemantic);
  3361. }
  3362. DepthKind = semanticKind;
  3363. break;
  3364. case DXIL::SemanticKind::Barycentrics: {
  3365. // There can only be up to two SV_Barycentrics
  3366. // with differeent perspective interpolation modes.
  3367. if (numBarycentrics++ > 1) {
  3368. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  3369. break;
  3370. }
  3371. const InterpolationMode *mode = E->GetInterpolationMode();
  3372. if (prevBaryInterpMode) {
  3373. if ((mode->IsAnyNoPerspective() && prevBaryInterpMode->IsAnyNoPerspective())
  3374. || (!mode->IsAnyNoPerspective() && !prevBaryInterpMode->IsAnyNoPerspective())) {
  3375. ValCtx.EmitError(ValidationRule::MetaBarycentricsTwoPerspectives);
  3376. }
  3377. }
  3378. prevBaryInterpMode = mode;
  3379. break;
  3380. }
  3381. default:
  3382. if (semanticUsageSet[streamId].count(semanticKind) > 0) {
  3383. ValCtx.EmitFormatError(ValidationRule::MetaDuplicateSysValue,
  3384. {E->GetSemantic()->GetName()});
  3385. }
  3386. semanticUsageSet[streamId].insert(semanticKind);
  3387. break;
  3388. }
  3389. // Packed element overlap check.
  3390. ValidateSignatureOverlap(*E.get(), maxScalars, allocator[streamId], ValCtx);
  3391. if (isOutput && semanticKind == DXIL::SemanticKind::Position) {
  3392. ValCtx.hasOutputPosition[E->GetOutputStream()] = true;
  3393. }
  3394. }
  3395. if (ValCtx.hasViewID && S.IsInput() && ValCtx.DxilMod.GetShaderModel()->GetKind() == DXIL::ShaderKind::Pixel) {
  3396. // Ensure sufficient space for ViewID:
  3397. DxilSignatureAllocator::DummyElement viewID;
  3398. viewID.rows = 1;
  3399. viewID.cols = 1;
  3400. viewID.kind = DXIL::SemanticKind::Arbitrary;
  3401. viewID.interpolation = DXIL::InterpolationMode::Constant;
  3402. viewID.interpretation = DXIL::SemanticInterpretationKind::SGV;
  3403. allocator[0].PackNext(&viewID, 0, 32);
  3404. if (!viewID.IsAllocated()) {
  3405. ValCtx.EmitError(ValidationRule::SmViewIDNeedsSlot);
  3406. }
  3407. }
  3408. }
  3409. static void ValidateNoInterpModeSignature(ValidationContext &ValCtx, const DxilSignature &S) {
  3410. for (auto &E : S.GetElements()) {
  3411. if (!E->GetInterpolationMode()->IsUndefined()) {
  3412. ValCtx.EmitSignatureError(E.get(), ValidationRule::SmNoInterpMode);
  3413. }
  3414. }
  3415. }
  3416. static void ValidateSignatures(ValidationContext &ValCtx) {
  3417. DxilModule &M = ValCtx.DxilMod;
  3418. bool isPS = M.GetShaderModel()->IsPS();
  3419. bool isVS = M.GetShaderModel()->IsVS();
  3420. bool isGS = M.GetShaderModel()->IsGS();
  3421. bool isCS = M.GetShaderModel()->IsCS();
  3422. if (isPS) {
  3423. // PS output no interp mode.
  3424. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature());
  3425. } else if (isVS) {
  3426. // VS input no interp mode.
  3427. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetInputSignature());
  3428. }
  3429. // patch constant no interp mode.
  3430. ValidateNoInterpModeSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature());
  3431. unsigned maxInputScalars = DXIL::kMaxInputTotalScalars;
  3432. unsigned maxOutputScalars = 0;
  3433. unsigned maxPatchConstantScalars = 0;
  3434. switch (M.GetShaderModel()->GetKind()) {
  3435. case DXIL::ShaderKind::Compute:
  3436. break;
  3437. case DXIL::ShaderKind::Vertex:
  3438. case DXIL::ShaderKind::Geometry:
  3439. case DXIL::ShaderKind::Pixel:
  3440. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3441. break;
  3442. case DXIL::ShaderKind::Hull:
  3443. case DXIL::ShaderKind::Domain:
  3444. maxOutputScalars = DXIL::kMaxOutputTotalScalars;
  3445. maxPatchConstantScalars = DXIL::kMaxHSOutputPatchConstantTotalScalars;
  3446. break;
  3447. default:
  3448. break;
  3449. }
  3450. ValidateSignature(ValCtx, ValCtx.DxilMod.GetInputSignature(), maxInputScalars);
  3451. ValidateSignature(ValCtx, ValCtx.DxilMod.GetOutputSignature(), maxOutputScalars);
  3452. ValidateSignature(ValCtx, ValCtx.DxilMod.GetPatchConstantSignature(), maxPatchConstantScalars);
  3453. if (isPS) {
  3454. // Gather execution information.
  3455. hlsl::PSExecutionInfo &PSExec = ValCtx.PSExec;
  3456. for (auto &E : ValCtx.DxilMod.GetInputSignature().GetElements()) {
  3457. if (E->GetKind() == DXIL::SemanticKind::SampleIndex) {
  3458. PSExec.SuperSampling = true;
  3459. continue;
  3460. }
  3461. const InterpolationMode *IM = E->GetInterpolationMode();
  3462. if (IM->IsLinearSample() || IM->IsLinearNoperspectiveSample()) {
  3463. PSExec.SuperSampling = true;
  3464. }
  3465. if (E->GetKind() == DXIL::SemanticKind::Position) {
  3466. PSExec.PositionInterpolationMode = IM;
  3467. }
  3468. }
  3469. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3470. if (E->IsAnyDepth()) {
  3471. PSExec.OutputDepthKind = E->GetKind();
  3472. break;
  3473. }
  3474. }
  3475. if (!PSExec.SuperSampling &&
  3476. PSExec.OutputDepthKind != DXIL::SemanticKind::Invalid &&
  3477. PSExec.OutputDepthKind != DXIL::SemanticKind::Depth) {
  3478. if (PSExec.PositionInterpolationMode != nullptr) {
  3479. if (!PSExec.PositionInterpolationMode->IsUndefined() &&
  3480. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveCentroid() &&
  3481. !PSExec.PositionInterpolationMode->IsLinearNoperspectiveSample()) {
  3482. ValCtx.EmitError(ValidationRule::SmPSConsistentInterp);
  3483. }
  3484. }
  3485. }
  3486. // Validate PS output semantic.
  3487. DxilSignature &outputSig = M.GetOutputSignature();
  3488. for (auto &SE : outputSig.GetElements()) {
  3489. Semantic::Kind semanticKind = SE->GetSemantic()->GetKind();
  3490. switch (semanticKind) {
  3491. case Semantic::Kind::Target:
  3492. case Semantic::Kind::Coverage:
  3493. case Semantic::Kind::Depth:
  3494. case Semantic::Kind::DepthGreaterEqual:
  3495. case Semantic::Kind::DepthLessEqual:
  3496. case Semantic::Kind::StencilRef:
  3497. break;
  3498. default: {
  3499. ValCtx.EmitFormatError(ValidationRule::SmPSOutputSemantic, {SE->GetName()});
  3500. } break;
  3501. }
  3502. }
  3503. }
  3504. if (isGS) {
  3505. unsigned maxVertexCount = M.GetMaxVertexCount();
  3506. unsigned outputScalarCount = 0;
  3507. DxilSignature &outSig = ValCtx.DxilMod.GetOutputSignature();
  3508. for (auto &SE : outSig.GetElements()) {
  3509. outputScalarCount += SE->GetRows() * SE->GetCols();
  3510. }
  3511. unsigned totalOutputScalars = maxVertexCount * outputScalarCount;
  3512. if (totalOutputScalars > DXIL::kMaxGSOutputTotalScalars) {
  3513. ValCtx.EmitFormatError(
  3514. ValidationRule::SmGSTotalOutputVertexDataRange,
  3515. {std::to_string(maxVertexCount),
  3516. std::to_string(outputScalarCount),
  3517. std::to_string(totalOutputScalars),
  3518. std::to_string(DXIL::kMaxGSOutputTotalScalars)});
  3519. }
  3520. }
  3521. if (isCS) {
  3522. if (!ValCtx.DxilMod.GetOutputSignature().GetElements().empty() ||
  3523. !ValCtx.DxilMod.GetPatchConstantSignature().GetElements().empty()) {
  3524. ValCtx.EmitError(ValidationRule::SmCSNoReturn);
  3525. }
  3526. }
  3527. }
  3528. static void CheckPatchConstantSemantic(ValidationContext &ValCtx)
  3529. {
  3530. bool isHS = ValCtx.DxilMod.GetShaderModel()->IsHS();
  3531. DXIL::TessellatorDomain domain = ValCtx.DxilMod.GetTessellatorDomain();
  3532. DxilSignature &patchConstantSig = ValCtx.DxilMod.GetPatchConstantSignature();
  3533. const unsigned kQuadEdgeSize = 4;
  3534. const unsigned kQuadInsideSize = 2;
  3535. const unsigned kQuadDomainLocSize = 2;
  3536. const unsigned kTriEdgeSize = 3;
  3537. const unsigned kTriInsideSize = 1;
  3538. const unsigned kTriDomainLocSize = 3;
  3539. const unsigned kIsolineEdgeSize = 2;
  3540. const unsigned kIsolineInsideSize = 0;
  3541. const unsigned kIsolineDomainLocSize = 3;
  3542. const char *domainName = "";
  3543. DXIL::SemanticKind kEdgeSemantic = DXIL::SemanticKind::TessFactor;
  3544. unsigned edgeSize = 0;
  3545. DXIL::SemanticKind kInsideSemantic = DXIL::SemanticKind::InsideTessFactor;
  3546. unsigned insideSize = 0;
  3547. ValCtx.domainLocSize = 0;
  3548. switch (domain) {
  3549. case DXIL::TessellatorDomain::IsoLine:
  3550. domainName = "IsoLine";
  3551. edgeSize = kIsolineEdgeSize;
  3552. insideSize = kIsolineInsideSize;
  3553. ValCtx.domainLocSize = kIsolineDomainLocSize;
  3554. break;
  3555. case DXIL::TessellatorDomain::Tri:
  3556. domainName = "Tri";
  3557. edgeSize = kTriEdgeSize;
  3558. insideSize = kTriInsideSize;
  3559. ValCtx.domainLocSize = kTriDomainLocSize;
  3560. break;
  3561. case DXIL::TessellatorDomain::Quad:
  3562. domainName = "Quad";
  3563. edgeSize = kQuadEdgeSize;
  3564. insideSize = kQuadInsideSize;
  3565. ValCtx.domainLocSize = kQuadDomainLocSize;
  3566. break;
  3567. default:
  3568. // Don't bother with other tests if domain is invalid
  3569. return;
  3570. }
  3571. bool bFoundEdgeSemantic = false;
  3572. bool bFoundInsideSemantic = false;
  3573. for (auto &SE : patchConstantSig.GetElements()) {
  3574. Semantic::Kind kind = SE->GetSemantic()->GetKind();
  3575. if (kind == kEdgeSemantic) {
  3576. bFoundEdgeSemantic = true;
  3577. if (SE->GetRows() != edgeSize || SE->GetCols() > 1) {
  3578. ValCtx.EmitFormatError(ValidationRule::SmTessFactorSizeMatchDomain,
  3579. {std::to_string(SE->GetRows()),
  3580. std::to_string(SE->GetCols()),
  3581. domainName,
  3582. std::to_string(edgeSize)});
  3583. }
  3584. } else if (kind == kInsideSemantic) {
  3585. bFoundInsideSemantic = true;
  3586. if (SE->GetRows() != insideSize || SE->GetCols() > 1) {
  3587. ValCtx.EmitFormatError(ValidationRule::SmInsideTessFactorSizeMatchDomain,
  3588. {std::to_string(SE->GetRows()),
  3589. std::to_string(SE->GetCols()),
  3590. domainName,
  3591. std::to_string(insideSize)});
  3592. }
  3593. }
  3594. }
  3595. if (isHS) {
  3596. if (!bFoundEdgeSemantic) {
  3597. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3598. }
  3599. if (!bFoundInsideSemantic && domain != DXIL::TessellatorDomain::IsoLine) {
  3600. ValCtx.EmitError(ValidationRule::SmTessFactorForDomain);
  3601. }
  3602. }
  3603. }
  3604. static void ValidateShaderState(ValidationContext &ValCtx) {
  3605. DxilModule &M = ValCtx.DxilMod;
  3606. DXIL::ShaderKind ShaderType = M.GetShaderModel()->GetKind();
  3607. if (ShaderType == DXIL::ShaderKind::Compute) {
  3608. unsigned x = M.m_NumThreads[0];
  3609. unsigned y = M.m_NumThreads[1];
  3610. unsigned z = M.m_NumThreads[2];
  3611. unsigned threadsInGroup = x * y * z;
  3612. if ((x < DXIL::kMinCSThreadGroupX) || (x > DXIL::kMaxCSThreadGroupX)) {
  3613. ValCtx.EmitFormatError(
  3614. ValidationRule::SmThreadGroupChannelRange,
  3615. {"X", std::to_string(x),
  3616. std::to_string(DXIL::kMinCSThreadGroupX),
  3617. std::to_string(DXIL::kMaxCSThreadGroupX)});
  3618. }
  3619. if ((y < DXIL::kMinCSThreadGroupY) || (y > DXIL::kMaxCSThreadGroupY)) {
  3620. ValCtx.EmitFormatError(
  3621. ValidationRule::SmThreadGroupChannelRange,
  3622. {"Y", std::to_string(y),
  3623. std::to_string(DXIL::kMinCSThreadGroupY),
  3624. std::to_string(DXIL::kMaxCSThreadGroupY)});
  3625. }
  3626. if ((z < DXIL::kMinCSThreadGroupZ) || (z > DXIL::kMaxCSThreadGroupZ)) {
  3627. ValCtx.EmitFormatError(
  3628. ValidationRule::SmThreadGroupChannelRange,
  3629. {"Z", std::to_string(z),
  3630. std::to_string(DXIL::kMinCSThreadGroupZ),
  3631. std::to_string(DXIL::kMaxCSThreadGroupZ)});
  3632. }
  3633. if (threadsInGroup > DXIL::kMaxCSThreadsPerGroup) {
  3634. ValCtx.EmitFormatError(
  3635. ValidationRule::SmMaxTheadGroup,
  3636. {std::to_string(threadsInGroup),
  3637. std::to_string(DXIL::kMaxCSThreadsPerGroup)});
  3638. }
  3639. // type of threadID, thread group ID take care by DXIL operation overload
  3640. // check.
  3641. } else if (ShaderType == DXIL::ShaderKind::Domain) {
  3642. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3643. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3644. domain = DXIL::TessellatorDomain::Undefined;
  3645. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3646. if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3647. ValCtx.EmitFormatError(
  3648. ValidationRule::SmDSInputControlPointCountRange,
  3649. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3650. std::to_string(inputControlPointCount)});
  3651. }
  3652. if (domain == DXIL::TessellatorDomain::Undefined) {
  3653. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3654. }
  3655. CheckPatchConstantSemantic(ValCtx);
  3656. } else if (ShaderType == DXIL::ShaderKind::Hull) {
  3657. DXIL::TessellatorDomain domain = M.GetTessellatorDomain();
  3658. if (domain >= DXIL::TessellatorDomain::LastEntry)
  3659. domain = DXIL::TessellatorDomain::Undefined;
  3660. unsigned inputControlPointCount = M.GetInputControlPointCount();
  3661. if (inputControlPointCount == 0) {
  3662. if (!M.GetInputSignature().GetElements().empty()) {
  3663. ValCtx.EmitError(
  3664. ValidationRule::SmZeroHSInputControlPointWithInput);
  3665. }
  3666. } else if (inputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3667. ValCtx.EmitFormatError(
  3668. ValidationRule::SmHSInputControlPointCountRange,
  3669. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3670. std::to_string(inputControlPointCount)});
  3671. }
  3672. if (domain == DXIL::TessellatorDomain::Undefined) {
  3673. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3674. }
  3675. DXIL::TessellatorPartitioning partition = M.GetTessellatorPartitioning();
  3676. if (partition == DXIL::TessellatorPartitioning::Undefined) {
  3677. ValCtx.EmitError(ValidationRule::MetaTessellatorPartition);
  3678. }
  3679. DXIL::TessellatorOutputPrimitive tessOutputPrimitive =
  3680. M.GetTessellatorOutputPrimitive();
  3681. if (tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::Undefined ||
  3682. tessOutputPrimitive == DXIL::TessellatorOutputPrimitive::LastEntry) {
  3683. ValCtx.EmitError(ValidationRule::MetaTessellatorOutputPrimitive);
  3684. }
  3685. float maxTessFactor = M.GetMaxTessellationFactor();
  3686. if (maxTessFactor < DXIL::kHSMaxTessFactorLowerBound ||
  3687. maxTessFactor > DXIL::kHSMaxTessFactorUpperBound) {
  3688. ValCtx.EmitFormatError(
  3689. ValidationRule::MetaMaxTessFactor,
  3690. {std::to_string(DXIL::kHSMaxTessFactorLowerBound),
  3691. std::to_string(DXIL::kHSMaxTessFactorUpperBound),
  3692. std::to_string(maxTessFactor)});
  3693. }
  3694. // Domain and OutPrimivtive match.
  3695. switch (domain) {
  3696. case DXIL::TessellatorDomain::IsoLine:
  3697. switch (tessOutputPrimitive) {
  3698. case DXIL::TessellatorOutputPrimitive::TriangleCW:
  3699. case DXIL::TessellatorOutputPrimitive::TriangleCCW:
  3700. ValCtx.EmitError(ValidationRule::SmIsoLineOutputPrimitiveMismatch);
  3701. break;
  3702. default:
  3703. break;
  3704. }
  3705. break;
  3706. case DXIL::TessellatorDomain::Tri:
  3707. switch (tessOutputPrimitive) {
  3708. case DXIL::TessellatorOutputPrimitive::Line:
  3709. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3710. break;
  3711. default:
  3712. break;
  3713. }
  3714. break;
  3715. case DXIL::TessellatorDomain::Quad:
  3716. switch (tessOutputPrimitive) {
  3717. case DXIL::TessellatorOutputPrimitive::Line:
  3718. ValCtx.EmitError(ValidationRule::SmTriOutputPrimitiveMismatch);
  3719. break;
  3720. default:
  3721. break;
  3722. }
  3723. break;
  3724. default:
  3725. ValCtx.EmitError(ValidationRule::SmValidDomain);
  3726. break;
  3727. }
  3728. // Check pass thru HS.
  3729. if (M.GetEntryFunction() == nullptr) {
  3730. if (M.GetShaderModel()->IsHS()) {
  3731. if (M.GetInputControlPointCount() < M.GetOutputControlPointCount()) {
  3732. ValCtx.EmitError(
  3733. ValidationRule::SmHullPassThruControlPointCountMatch);
  3734. }
  3735. // Check declared control point outputs storage amounts are ok to pass
  3736. // through (less output storage than input for control points).
  3737. DxilSignature &outSig = M.GetOutputSignature();
  3738. unsigned totalOutputCPScalars = 0;
  3739. for (auto &SE : outSig.GetElements()) {
  3740. totalOutputCPScalars += SE->GetRows() * SE->GetCols();
  3741. }
  3742. if (totalOutputCPScalars * M.GetOutputControlPointCount() >
  3743. DXIL::kMaxHSOutputControlPointsTotalScalars) {
  3744. ValCtx.EmitError(ValidationRule::SmOutputControlPointsTotalScalars);
  3745. }
  3746. } else {
  3747. ValCtx.EmitError(ValidationRule::MetaEntryFunction);
  3748. }
  3749. }
  3750. CheckPatchConstantSemantic(ValCtx);
  3751. } else if (ShaderType == DXIL::ShaderKind::Geometry) {
  3752. unsigned maxVertexCount = M.GetMaxVertexCount();
  3753. if (maxVertexCount > DXIL::kMaxGSOutputVertexCount) {
  3754. ValCtx.EmitFormatError(
  3755. ValidationRule::SmGSOutputVertexCountRange,
  3756. {std::to_string(DXIL::kMaxGSOutputVertexCount),
  3757. std::to_string(maxVertexCount)});
  3758. }
  3759. unsigned instanceCount = M.GetGSInstanceCount();
  3760. if (instanceCount > DXIL::kMaxGSInstanceCount || instanceCount < 1) {
  3761. ValCtx.EmitFormatError(ValidationRule::SmGSInstanceCountRange,
  3762. {std::to_string(DXIL::kMaxGSInstanceCount),
  3763. std::to_string(instanceCount)});
  3764. }
  3765. DXIL::PrimitiveTopology topo = M.GetStreamPrimitiveTopology();
  3766. switch (topo) {
  3767. case DXIL::PrimitiveTopology::PointList:
  3768. case DXIL::PrimitiveTopology::LineStrip:
  3769. case DXIL::PrimitiveTopology::TriangleStrip:
  3770. break;
  3771. default: {
  3772. ValCtx.EmitError(ValidationRule::SmGSValidOutputPrimitiveTopology);
  3773. } break;
  3774. }
  3775. DXIL::InputPrimitive inputPrimitive = M.GetInputPrimitive();
  3776. unsigned VertexCount = GetNumVertices(inputPrimitive);
  3777. if (VertexCount == 0 && inputPrimitive != DXIL::InputPrimitive::Undefined) {
  3778. ValCtx.EmitError(ValidationRule::SmGSValidInputPrimitive);
  3779. }
  3780. }
  3781. unsigned outputControlPointCount = M.GetOutputControlPointCount();
  3782. if (outputControlPointCount > DXIL::kMaxIAPatchControlPointCount) {
  3783. ValCtx.EmitFormatError(
  3784. ValidationRule::SmOutputControlPointCountRange,
  3785. {std::to_string(DXIL::kMaxIAPatchControlPointCount),
  3786. std::to_string(outputControlPointCount)});
  3787. }
  3788. }
  3789. static bool
  3790. CalculateCallDepth(CallGraphNode *node,
  3791. std::unordered_map<CallGraphNode *, unsigned> &depthMap,
  3792. std::unordered_set<CallGraphNode *> &callStack,
  3793. std::unordered_set<Function *> &funcSet) {
  3794. unsigned depth = callStack.size();
  3795. funcSet.insert(node->getFunction());
  3796. for (auto it = node->begin(), ei = node->end(); it != ei; it++) {
  3797. CallGraphNode *toNode = it->second;
  3798. if (callStack.insert(toNode).second == false) {
  3799. // Recursive.
  3800. return true;
  3801. }
  3802. if (depthMap[toNode] < depth)
  3803. depthMap[toNode] = depth;
  3804. if (CalculateCallDepth(toNode, depthMap, callStack, funcSet)) {
  3805. // Recursive
  3806. return true;
  3807. }
  3808. callStack.erase(toNode);
  3809. }
  3810. return false;
  3811. }
  3812. static void ValidateCallGraph(ValidationContext &ValCtx) {
  3813. // Build CallGraph.
  3814. CallGraph CG(*ValCtx.DxilMod.GetModule());
  3815. std::unordered_map<CallGraphNode*, unsigned> depthMap;
  3816. std::unordered_set<CallGraphNode*> callStack;
  3817. CallGraphNode *entryNode = CG[ValCtx.DxilMod.GetEntryFunction()];
  3818. depthMap[entryNode] = 0;
  3819. bool bRecursive = CalculateCallDepth(entryNode, depthMap, callStack, ValCtx.entryFuncCallSet);
  3820. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3821. CallGraphNode *patchConstantNode = CG[ValCtx.DxilMod.GetPatchConstantFunction()];
  3822. depthMap[patchConstantNode] = 0;
  3823. callStack.clear();
  3824. bRecursive |= CalculateCallDepth(patchConstantNode, depthMap, callStack, ValCtx.patchConstFuncCallSet);
  3825. }
  3826. if (bRecursive) {
  3827. ValCtx.EmitError(ValidationRule::FlowNoRecusion);
  3828. }
  3829. }
  3830. static void ValidateFlowControl(ValidationContext &ValCtx) {
  3831. bool reducible =
  3832. IsReducible(*ValCtx.DxilMod.GetModule(), IrreducibilityAction::Ignore);
  3833. if (!reducible) {
  3834. ValCtx.EmitError(ValidationRule::FlowReducible);
  3835. return;
  3836. }
  3837. ValidateCallGraph(ValCtx);
  3838. for (auto &F : ValCtx.DxilMod.GetModule()->functions()) {
  3839. if (F.isDeclaration())
  3840. continue;
  3841. DominatorTreeAnalysis DTA;
  3842. DominatorTree DT = DTA.run(F);
  3843. LoopInfo LI;
  3844. LI.Analyze(DT);
  3845. for (auto loopIt = LI.begin(); loopIt != LI.end(); loopIt++) {
  3846. Loop *loop = *loopIt;
  3847. SmallVector<BasicBlock *, 4> exitBlocks;
  3848. loop->getExitBlocks(exitBlocks);
  3849. if (exitBlocks.empty())
  3850. ValCtx.EmitError(ValidationRule::FlowDeadLoop);
  3851. }
  3852. }
  3853. // fxc has ERR_CONTINUE_INSIDE_SWITCH to disallow continue in switch.
  3854. // Not do it for now.
  3855. }
  3856. static void ValidateUninitializedOutput(ValidationContext &ValCtx) {
  3857. // For HS only need to check Tessfactor which is in patch constant sig.
  3858. if (ValCtx.DxilMod.GetShaderModel()->IsHS()) {
  3859. std::vector<unsigned> &patchConstCols = ValCtx.patchConstCols;
  3860. for (auto &E : ValCtx.DxilMod.GetPatchConstantSignature().GetElements()) {
  3861. unsigned mask = patchConstCols[E->GetID()];
  3862. unsigned requireMask = (1 << E->GetCols()) - 1;
  3863. // TODO: check other case uninitialized output is allowed.
  3864. if (mask != requireMask && !E->GetSemantic()->IsArbitrary()) {
  3865. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput,
  3866. {E->GetName()});
  3867. }
  3868. }
  3869. return;
  3870. }
  3871. std::vector<unsigned> &outputCols = ValCtx.outputCols;
  3872. for (auto &E : ValCtx.DxilMod.GetOutputSignature().GetElements()) {
  3873. unsigned mask = outputCols[E->GetID()];
  3874. unsigned requireMask = (1 << E->GetCols()) - 1;
  3875. // TODO: check other case uninitialized output is allowed.
  3876. if (mask != requireMask && !E->GetSemantic()->IsArbitrary() &&
  3877. E->GetSemantic()->GetKind() != Semantic::Kind::Target) {
  3878. ValCtx.EmitFormatError(ValidationRule::SmUndefinedOutput, {E->GetName()});
  3879. }
  3880. }
  3881. }
  3882. void GetValidationVersion(_Out_ unsigned *pMajor, _Out_ unsigned *pMinor) {
  3883. // 1.0 is the first validator.
  3884. // 1.1 adds:
  3885. // - ILDN container part support
  3886. // 1.2 adds:
  3887. // - Metadata for floating point denorm mode
  3888. *pMajor = 1;
  3889. *pMinor = 2;
  3890. }
  3891. _Use_decl_annotations_ HRESULT
  3892. ValidateDxilModule(llvm::Module *pModule, llvm::Module *pDebugModule) {
  3893. std::string diagStr;
  3894. raw_string_ostream diagStream(diagStr);
  3895. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3896. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  3897. if (!pDxilModule) {
  3898. return DXC_E_IR_VERIFICATION_FAILED;
  3899. }
  3900. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  3901. ValidateMetadata(ValCtx);
  3902. ValidateShaderState(ValCtx);
  3903. ValidateGlobalVariables(ValCtx);
  3904. ValidateResources(ValCtx);
  3905. // Validate control flow and collect function call info.
  3906. // If has recursive call, call info collection will not finish.
  3907. ValidateFlowControl(ValCtx);
  3908. // Validate functions.
  3909. for (Function &F : pModule->functions()) {
  3910. ValidateFunction(F, ValCtx);
  3911. }
  3912. ValidateUninitializedOutput(ValCtx);
  3913. ValidateShaderFlags(ValCtx);
  3914. ValidateSignatures(ValCtx);
  3915. if (!pDxilModule->GetShaderModel()->IsGS()) {
  3916. unsigned posMask = ValCtx.OutputPositionMask[0];
  3917. if (posMask != 0xf && ValCtx.hasOutputPosition[0]) {
  3918. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3919. }
  3920. } else {
  3921. unsigned streamMask = ValCtx.DxilMod.GetActiveStreamMask();
  3922. for (unsigned i = 0; i < DXIL::kNumOutputStreams; i++) {
  3923. if (streamMask & (1 << i)) {
  3924. unsigned posMask = ValCtx.OutputPositionMask[i];
  3925. if (posMask != 0xf && ValCtx.hasOutputPosition[i]) {
  3926. ValCtx.EmitError(ValidationRule::SmCompletePosition);
  3927. }
  3928. }
  3929. }
  3930. }
  3931. // Ensure error messages are flushed out on error.
  3932. if (ValCtx.Failed) {
  3933. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  3934. return DXC_E_IR_VERIFICATION_FAILED;
  3935. }
  3936. return S_OK;
  3937. }
  3938. // DXIL Container Verification Functions
  3939. static void VerifyBlobPartMatches(_In_ ValidationContext &ValCtx,
  3940. _In_ LPCSTR pName,
  3941. DxilPartWriter *pWriter,
  3942. _In_reads_bytes_opt_(Size) const void *pData,
  3943. _In_ uint32_t Size) {
  3944. if (!pData && pWriter->size()) {
  3945. // No blob part, but writer says non-zero size is expected.
  3946. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {pName});
  3947. return;
  3948. }
  3949. // Compare sizes
  3950. if (pWriter->size() != Size) {
  3951. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  3952. return;
  3953. }
  3954. if (Size == 0) {
  3955. return;
  3956. }
  3957. CComPtr<AbstractMemoryStream> pOutputStream;
  3958. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  3959. pOutputStream->Reserve(Size);
  3960. pWriter->write(pOutputStream);
  3961. DXASSERT(pOutputStream->GetPtrSize() == Size, "otherwise, DxilPartWriter misreported size");
  3962. if (memcmp(pData, pOutputStream->GetPtr(), Size)) {
  3963. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {pName});
  3964. return;
  3965. }
  3966. return;
  3967. }
  3968. static void VerifySignatureMatches(_In_ ValidationContext &ValCtx,
  3969. DXIL::SignatureKind SigKind,
  3970. _In_reads_bytes_opt_(SigSize) const void *pSigData,
  3971. _In_ uint32_t SigSize) {
  3972. // Generate corresponding signature from module and memcmp
  3973. const char *pName = nullptr;
  3974. switch (SigKind)
  3975. {
  3976. case hlsl::DXIL::SignatureKind::Input:
  3977. pName = "Program Input Signature";
  3978. break;
  3979. case hlsl::DXIL::SignatureKind::Output:
  3980. pName = "Program Output Signature";
  3981. break;
  3982. case hlsl::DXIL::SignatureKind::PatchConstant:
  3983. pName = "Program Patch Constant Signature";
  3984. break;
  3985. default:
  3986. break;
  3987. }
  3988. unique_ptr<DxilPartWriter> pWriter(NewProgramSignatureWriter(ValCtx.DxilMod, SigKind));
  3989. VerifyBlobPartMatches(ValCtx, pName, pWriter.get(), pSigData, SigSize);
  3990. }
  3991. _Use_decl_annotations_
  3992. bool VerifySignatureMatches(llvm::Module *pModule,
  3993. DXIL::SignatureKind SigKind,
  3994. const void *pSigData,
  3995. uint32_t SigSize) {
  3996. std::string diagStr;
  3997. raw_string_ostream diagStream(diagStr);
  3998. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  3999. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  4000. VerifySignatureMatches(ValCtx, SigKind, pSigData, SigSize);
  4001. if (ValCtx.Failed) {
  4002. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  4003. }
  4004. return !ValCtx.Failed;
  4005. }
  4006. static void VerifyPSVMatches(_In_ ValidationContext &ValCtx,
  4007. _In_reads_bytes_(PSVSize) const void *pPSVData,
  4008. _In_ uint32_t PSVSize) {
  4009. uint32_t PSVVersion = 1; // This should be set to the newest version
  4010. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  4011. // Try each version in case an earlier version matches module
  4012. while (PSVVersion && pWriter->size() != PSVSize) {
  4013. PSVVersion --;
  4014. pWriter.reset(NewPSVWriter(ValCtx.DxilMod, PSVVersion));
  4015. }
  4016. // generate PSV data from module and memcmp
  4017. VerifyBlobPartMatches(ValCtx, "Pipeline State Validation", pWriter.get(), pPSVData, PSVSize);
  4018. }
  4019. _Use_decl_annotations_
  4020. bool VerifyPSVMatches(llvm::Module *pModule,
  4021. const void *pPSVData,
  4022. uint32_t PSVSize) {
  4023. std::string diagStr;
  4024. raw_string_ostream diagStream(diagStr);
  4025. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  4026. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  4027. VerifyPSVMatches(ValCtx, pPSVData, PSVSize);
  4028. if (ValCtx.Failed) {
  4029. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  4030. }
  4031. return !ValCtx.Failed;
  4032. }
  4033. static void VerifyFeatureInfoMatches(_In_ ValidationContext &ValCtx,
  4034. _In_reads_bytes_(FeatureInfoSize) const void *pFeatureInfoData,
  4035. _In_ uint32_t FeatureInfoSize) {
  4036. // generate Feature Info data from module and memcmp
  4037. unique_ptr<DxilPartWriter> pWriter(NewFeatureInfoWriter(ValCtx.DxilMod));
  4038. VerifyBlobPartMatches(ValCtx, "Feature Info", pWriter.get(), pFeatureInfoData, FeatureInfoSize);
  4039. }
  4040. _Use_decl_annotations_
  4041. bool VerifyFeatureInfoMatches(llvm::Module *pModule,
  4042. const void *pFeatureInfoData,
  4043. uint32_t FeatureInfoSize) {
  4044. std::string diagStr;
  4045. raw_string_ostream diagStream(diagStr);
  4046. DiagnosticPrinterRawOStream DiagPrinter(diagStream);
  4047. ValidationContext ValCtx(*pModule, nullptr, pModule->GetOrCreateDxilModule(), DiagPrinter);
  4048. VerifyFeatureInfoMatches(ValCtx, pFeatureInfoData, FeatureInfoSize);
  4049. if (ValCtx.Failed) {
  4050. emitDxilDiag(pModule->getContext(), diagStream.str().c_str());
  4051. }
  4052. return !ValCtx.Failed;
  4053. }
  4054. _Use_decl_annotations_
  4055. HRESULT ValidateDxilContainerParts(llvm::Module *pModule,
  4056. llvm::Module *pDebugModule,
  4057. const DxilContainerHeader *pContainer,
  4058. uint32_t ContainerSize) {
  4059. DXASSERT_NOMSG(pModule);
  4060. if (!pContainer || !IsValidDxilContainer(pContainer, ContainerSize)) {
  4061. return DXC_E_CONTAINER_INVALID;
  4062. }
  4063. DxilModule *pDxilModule = DxilModule::TryGetDxilModule(pModule);
  4064. if (!pDxilModule) {
  4065. return DXC_E_IR_VERIFICATION_FAILED;
  4066. }
  4067. std::string diagStr;
  4068. raw_string_ostream DiagStream(diagStr);
  4069. DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4070. ValidationContext ValCtx(*pModule, pDebugModule, *pDxilModule, DiagPrinter);
  4071. DXIL::ShaderKind ShaderKind = pDxilModule->GetShaderModel()->GetKind();
  4072. bool bTess = ShaderKind == DXIL::ShaderKind::Hull || ShaderKind == DXIL::ShaderKind::Domain;
  4073. std::unordered_set<uint32_t> FourCCFound;
  4074. const DxilPartHeader *pRootSignaturePart = nullptr;
  4075. const DxilPartHeader *pPSVPart = nullptr;
  4076. for (auto it = begin(pContainer), itEnd = end(pContainer); it != itEnd; ++it) {
  4077. const DxilPartHeader *pPart = *it;
  4078. char szFourCC[5];
  4079. PartKindToCharArray(pPart->PartFourCC, szFourCC);
  4080. if (FourCCFound.find(pPart->PartFourCC) != FourCCFound.end()) {
  4081. // Two parts with same FourCC found
  4082. ValCtx.EmitFormatError(ValidationRule::ContainerPartRepeated, {szFourCC});
  4083. continue;
  4084. }
  4085. FourCCFound.insert(pPart->PartFourCC);
  4086. switch (pPart->PartFourCC)
  4087. {
  4088. case DFCC_InputSignature:
  4089. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, GetDxilPartData(pPart), pPart->PartSize);
  4090. break;
  4091. case DFCC_OutputSignature:
  4092. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, GetDxilPartData(pPart), pPart->PartSize);
  4093. break;
  4094. case DFCC_PatchConstantSignature:
  4095. if (bTess) {
  4096. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::PatchConstant, GetDxilPartData(pPart), pPart->PartSize);
  4097. } else {
  4098. ValCtx.EmitFormatError(ValidationRule::ContainerPartMatches, {"Program Patch Constant Signature"});
  4099. }
  4100. break;
  4101. case DFCC_FeatureInfo:
  4102. VerifyFeatureInfoMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  4103. break;
  4104. case DFCC_RootSignature:
  4105. pRootSignaturePart = pPart;
  4106. break;
  4107. case DFCC_PipelineStateValidation:
  4108. pPSVPart = pPart;
  4109. VerifyPSVMatches(ValCtx, GetDxilPartData(pPart), pPart->PartSize);
  4110. break;
  4111. // Skip these
  4112. case DFCC_ResourceDef:
  4113. case DFCC_ShaderStatistics:
  4114. case DFCC_PrivateData:
  4115. case DFCC_DXIL:
  4116. case DFCC_ShaderDebugInfoDXIL:
  4117. case DFCC_ShaderDebugName:
  4118. continue;
  4119. case DFCC_Container:
  4120. default:
  4121. ValCtx.EmitFormatError(ValidationRule::ContainerPartInvalid, {szFourCC});
  4122. break;
  4123. }
  4124. }
  4125. // Verify required parts found
  4126. if (FourCCFound.find(DFCC_InputSignature) == FourCCFound.end()) {
  4127. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Input, nullptr, 0);
  4128. }
  4129. if (FourCCFound.find(DFCC_OutputSignature) == FourCCFound.end()) {
  4130. VerifySignatureMatches(ValCtx, DXIL::SignatureKind::Output, nullptr, 0);
  4131. }
  4132. if (bTess && FourCCFound.find(DFCC_PatchConstantSignature) == FourCCFound.end() &&
  4133. pDxilModule->GetPatchConstantSignature().GetElements().size())
  4134. {
  4135. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Program Patch Constant Signature"});
  4136. }
  4137. if (FourCCFound.find(DFCC_FeatureInfo) == FourCCFound.end()) {
  4138. // Could be optional, but RS1 runtime doesn't handle this case properly.
  4139. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Feature Info"});
  4140. }
  4141. // Validate Root Signature
  4142. if (pPSVPart) {
  4143. if (pRootSignaturePart) {
  4144. try {
  4145. RootSignatureHandle RS;
  4146. RS.LoadSerialized((const uint8_t*)GetDxilPartData(pRootSignaturePart), pRootSignaturePart->PartSize);
  4147. RS.Deserialize();
  4148. IFTBOOL(VerifyRootSignatureWithShaderPSV(RS.GetDesc(),
  4149. pDxilModule->GetShaderModel()->GetKind(),
  4150. GetDxilPartData(pPSVPart), pPSVPart->PartSize,
  4151. DiagStream), DXC_E_INCORRECT_ROOT_SIGNATURE);
  4152. } catch (...) {
  4153. ValCtx.EmitError(ValidationRule::ContainerRootSignatureIncompatible);
  4154. }
  4155. }
  4156. } else {
  4157. ValCtx.EmitFormatError(ValidationRule::ContainerPartMissing, {"Pipeline State Validation"});
  4158. }
  4159. if (ValCtx.Failed) {
  4160. emitDxilDiag(pModule->getContext(), DiagStream.str().c_str());
  4161. return DXC_E_MALFORMED_CONTAINER;
  4162. }
  4163. return S_OK;
  4164. }
  4165. static HRESULT FindDxilPart(_In_reads_bytes_(ContainerSize) const void *pContainerBytes,
  4166. _In_ uint32_t ContainerSize,
  4167. _In_ DxilFourCC FourCC,
  4168. _In_ const DxilPartHeader **ppPart) {
  4169. const DxilContainerHeader *pContainer =
  4170. IsDxilContainerLike(pContainerBytes, ContainerSize);
  4171. if (!pContainer) {
  4172. IFR(DXC_E_CONTAINER_INVALID);
  4173. }
  4174. if (!IsValidDxilContainer(pContainer, ContainerSize)) {
  4175. IFR(DXC_E_CONTAINER_INVALID);
  4176. }
  4177. DxilPartIterator it = std::find_if(begin(pContainer), end(pContainer),
  4178. DxilPartIsType(FourCC));
  4179. if (it == end(pContainer)) {
  4180. IFR(DXC_E_CONTAINER_MISSING_DXIL);
  4181. }
  4182. const DxilProgramHeader *pProgramHeader =
  4183. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(*it));
  4184. if (!IsValidDxilProgramHeader(pProgramHeader, (*it)->PartSize)) {
  4185. IFR(DXC_E_CONTAINER_INVALID);
  4186. }
  4187. *ppPart = *it;
  4188. return S_OK;
  4189. }
  4190. _Use_decl_annotations_
  4191. HRESULT ValidateLoadModule(const char *pIL,
  4192. uint32_t ILLength,
  4193. unique_ptr<llvm::Module> &pModule,
  4194. LLVMContext &Ctx,
  4195. llvm::raw_ostream &DiagStream,
  4196. unsigned bLazyLoad) {
  4197. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4198. PrintDiagnosticContext DiagContext(DiagPrinter);
  4199. DiagRestore DR(Ctx, &DiagContext);
  4200. std::unique_ptr<llvm::MemoryBuffer> pBitcodeBuf;
  4201. pBitcodeBuf.reset(llvm::MemoryBuffer::getMemBuffer(
  4202. llvm::StringRef(pIL, ILLength), "", false).release());
  4203. ErrorOr<std::unique_ptr<Module>> loadedModuleResult =
  4204. bLazyLoad == 0?
  4205. llvm::parseBitcodeFile(pBitcodeBuf->getMemBufferRef(), Ctx) :
  4206. llvm::getLazyBitcodeModule(std::move(pBitcodeBuf), Ctx);
  4207. // DXIL disallows some LLVM bitcode constructs, like unaccounted-for sub-blocks.
  4208. // These appear as warnings, which the validator should reject.
  4209. if (DiagContext.HasErrors() || DiagContext.HasWarnings() || loadedModuleResult.getError())
  4210. return DXC_E_IR_VERIFICATION_FAILED;
  4211. pModule = std::move(loadedModuleResult.get());
  4212. return S_OK;
  4213. }
  4214. HRESULT ValidateDxilBitcode(
  4215. _In_reads_bytes_(ILLength) const char *pIL,
  4216. _In_ uint32_t ILLength,
  4217. _In_ llvm::raw_ostream &DiagStream) {
  4218. LLVMContext Ctx;
  4219. std::unique_ptr<llvm::Module> pModule;
  4220. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4221. PrintDiagnosticContext DiagContext(DiagPrinter);
  4222. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4223. &DiagContext, true);
  4224. HRESULT hr;
  4225. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream,
  4226. /*bLazyLoad*/ false)))
  4227. return hr;
  4228. if (FAILED(hr = ValidateDxilModule(pModule.get(), nullptr)))
  4229. return hr;
  4230. DxilModule &dxilModule = pModule->GetDxilModule();
  4231. if (!dxilModule.GetRootSignature().IsEmpty()) {
  4232. unique_ptr<DxilPartWriter> pWriter(NewPSVWriter(dxilModule, 0));
  4233. DXASSERT_NOMSG(pWriter->size());
  4234. CComPtr<AbstractMemoryStream> pOutputStream;
  4235. IFT(CreateMemoryStream(DxcGetThreadMallocNoRef(), &pOutputStream));
  4236. pOutputStream->Reserve(pWriter->size());
  4237. pWriter->write(pOutputStream);
  4238. const DxilVersionedRootSignatureDesc* pDesc = dxilModule.GetRootSignature().GetDesc();
  4239. RootSignatureHandle RS;
  4240. try {
  4241. if (!pDesc) {
  4242. RS.Assign(nullptr, dxilModule.GetRootSignature().GetSerialized());
  4243. RS.Deserialize();
  4244. pDesc = RS.GetDesc();
  4245. if (!pDesc)
  4246. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  4247. }
  4248. IFTBOOL(VerifyRootSignatureWithShaderPSV(pDesc,
  4249. dxilModule.GetShaderModel()->GetKind(),
  4250. pOutputStream->GetPtr(), pWriter->size(),
  4251. DiagStream), DXC_E_INCORRECT_ROOT_SIGNATURE);
  4252. } catch (...) {
  4253. return DXC_E_INCORRECT_ROOT_SIGNATURE;
  4254. }
  4255. }
  4256. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  4257. return DXC_E_IR_VERIFICATION_FAILED;
  4258. }
  4259. return S_OK;
  4260. }
  4261. static HRESULT ValidateLoadModuleFromContainer(
  4262. _In_reads_bytes_(ILLength) const void *pContainer,
  4263. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4264. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4265. _In_ llvm::LLVMContext &Ctx, LLVMContext &DbgCtx,
  4266. _In_ llvm::raw_ostream &DiagStream, _In_ unsigned bLazyLoad) {
  4267. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4268. PrintDiagnosticContext DiagContext(DiagPrinter);
  4269. DiagRestore DR(Ctx, &DiagContext);
  4270. DiagRestore DR2(DbgCtx, &DiagContext);
  4271. const DxilPartHeader *pPart = nullptr;
  4272. IFR(FindDxilPart(pContainer, ContainerSize, DFCC_DXIL, &pPart));
  4273. const char *pIL = nullptr;
  4274. uint32_t ILLength = 0;
  4275. GetDxilProgramBitcode(
  4276. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pPart)), &pIL,
  4277. &ILLength);
  4278. IFR(ValidateLoadModule(pIL, ILLength, pModule, Ctx, DiagStream, bLazyLoad));
  4279. HRESULT hr;
  4280. const DxilPartHeader *pDbgPart = nullptr;
  4281. if (FAILED(hr = FindDxilPart(pContainer, ContainerSize,
  4282. DFCC_ShaderDebugInfoDXIL, &pDbgPart)) &&
  4283. hr != DXC_E_CONTAINER_MISSING_DXIL) {
  4284. return hr;
  4285. }
  4286. if (pDbgPart) {
  4287. GetDxilProgramBitcode(
  4288. reinterpret_cast<const DxilProgramHeader *>(GetDxilPartData(pDbgPart)),
  4289. &pIL, &ILLength);
  4290. if (FAILED(hr = ValidateLoadModule(pIL, ILLength, pDebugModule, DbgCtx,
  4291. DiagStream, bLazyLoad))) {
  4292. return hr;
  4293. }
  4294. }
  4295. return S_OK;
  4296. }
  4297. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainer(
  4298. _In_reads_bytes_(ContainerSize) const void *pContainer,
  4299. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4300. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4301. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  4302. _In_ llvm::raw_ostream &DiagStream) {
  4303. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  4304. pDebugModule, Ctx, DbgCtx, DiagStream,
  4305. /*bLazyLoad*/ false);
  4306. }
  4307. // Lazy loads module from container, validating load, but not module.
  4308. _Use_decl_annotations_ HRESULT ValidateLoadModuleFromContainerLazy(
  4309. _In_reads_bytes_(ContainerSize) const void *pContainer,
  4310. _In_ uint32_t ContainerSize, _In_ std::unique_ptr<llvm::Module> &pModule,
  4311. _In_ std::unique_ptr<llvm::Module> &pDebugModule,
  4312. _In_ llvm::LLVMContext &Ctx, llvm::LLVMContext &DbgCtx,
  4313. _In_ llvm::raw_ostream &DiagStream) {
  4314. return ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule,
  4315. pDebugModule, Ctx, DbgCtx, DiagStream,
  4316. /*bLazyLoad*/ true);
  4317. }
  4318. _Use_decl_annotations_
  4319. HRESULT ValidateDxilContainer(const void *pContainer,
  4320. uint32_t ContainerSize,
  4321. llvm::raw_ostream &DiagStream) {
  4322. LLVMContext Ctx, DbgCtx;
  4323. std::unique_ptr<llvm::Module> pModule, pDebugModule;
  4324. llvm::DiagnosticPrinterRawOStream DiagPrinter(DiagStream);
  4325. PrintDiagnosticContext DiagContext(DiagPrinter);
  4326. Ctx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4327. &DiagContext, true);
  4328. DbgCtx.setDiagnosticHandler(PrintDiagnosticContext::PrintDiagnosticHandler,
  4329. &DiagContext, true);
  4330. IFR(ValidateLoadModuleFromContainer(pContainer, ContainerSize, pModule, pDebugModule,
  4331. Ctx, DbgCtx, DiagStream));
  4332. // Validate DXIL Module
  4333. IFR(ValidateDxilModule(pModule.get(), pDebugModule.get()));
  4334. if (DiagContext.HasErrors() || DiagContext.HasWarnings()) {
  4335. return DXC_E_IR_VERIFICATION_FAILED;
  4336. }
  4337. return ValidateDxilContainerParts(pModule.get(), pDebugModule.get(),
  4338. IsDxilContainerLike(pContainer, ContainerSize), ContainerSize);
  4339. }
  4340. } // namespace hlsl