DxilValidation.cpp 176 KB

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