DxilValidation.cpp 182 KB

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