DxilValidation.cpp 185 KB

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