DxilValidation.cpp 177 KB

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