DxilValidation.cpp 186 KB

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