DxilContainerReflection.cpp 102 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilContainerReflection.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. // Provides support for reading DXIL container structures. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/Bitcode/ReaderWriter.h"
  13. #include "llvm/IR/LLVMContext.h"
  14. #include "llvm/IR/InstIterator.h"
  15. #include "llvm/IR/Operator.h"
  16. #include "dxc/DxilContainer/DxilContainer.h"
  17. #include "dxc/DXIL/DxilModule.h"
  18. #include "dxc/DXIL/DxilShaderModel.h"
  19. #include "dxc/DXIL/DxilOperations.h"
  20. #include "dxc/DXIL/DxilInstructions.h"
  21. #include "dxc/Support/Global.h"
  22. #include "dxc/Support/Unicode.h"
  23. #include "dxc/Support/WinIncludes.h"
  24. #include "dxc/Support/microcom.h"
  25. #include "dxc/Support/FileIOHelper.h"
  26. #include "dxc/Support/dxcapi.impl.h"
  27. #include "dxc/DXIL/DxilFunctionProps.h"
  28. #include "dxc/DXIL/DxilPDB.h"
  29. #include "dxc/DXIL/DxilUtil.h"
  30. #include "dxc/HLSL/HLMatrixType.h"
  31. #include "dxc/DXIL/DxilCounters.h"
  32. #include <unordered_set>
  33. #include "llvm/ADT/SetVector.h"
  34. #include "dxc/dxcapi.h"
  35. #ifdef LLVM_ON_WIN32
  36. #include "d3d12shader.h" // for compatibility
  37. #include "d3d11shader.h" // for compatibility
  38. #include "dxc/DxilContainer/DxilRuntimeReflection.h"
  39. // Remove this workaround once newer version of d3dcommon.h can be compiled against
  40. #define ADD_16_64_BIT_TYPES
  41. // Disable warning about value not being valid in enum
  42. #pragma warning( disable : 4063 )
  43. const GUID IID_ID3D11ShaderReflection_43 = {
  44. 0x0a233719,
  45. 0x3960,
  46. 0x4578,
  47. {0x9d, 0x7c, 0x20, 0x3b, 0x8b, 0x1d, 0x9c, 0xc1}};
  48. const GUID IID_ID3D11ShaderReflection_47 = {
  49. 0x8d536ca1,
  50. 0x0cca,
  51. 0x4956,
  52. {0xa8, 0x37, 0x78, 0x69, 0x63, 0x75, 0x55, 0x84}};
  53. using namespace llvm;
  54. using namespace hlsl;
  55. using namespace hlsl::DXIL;
  56. class DxilContainerReflection : public IDxcContainerReflection {
  57. private:
  58. DXC_MICROCOM_TM_REF_FIELDS()
  59. CComPtr<IDxcBlob> m_container;
  60. const DxilContainerHeader *m_pHeader = nullptr;
  61. uint32_t m_headerLen = 0;
  62. bool IsLoaded() const { return m_pHeader != nullptr; }
  63. public:
  64. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  65. DXC_MICROCOM_TM_CTOR(DxilContainerReflection)
  66. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  67. return DoBasicQueryInterface<IDxcContainerReflection>(this, iid, ppvObject);
  68. }
  69. HRESULT STDMETHODCALLTYPE Load(_In_ IDxcBlob *pContainer) override;
  70. HRESULT STDMETHODCALLTYPE GetPartCount(_Out_ UINT32 *pResult) override;
  71. HRESULT STDMETHODCALLTYPE GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) override;
  72. HRESULT STDMETHODCALLTYPE GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) override;
  73. HRESULT STDMETHODCALLTYPE FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) override;
  74. HRESULT STDMETHODCALLTYPE GetPartReflection(UINT32 idx, REFIID iid, _COM_Outptr_ void **ppvObject) override;
  75. };
  76. class CShaderReflectionConstantBuffer;
  77. class CShaderReflectionType;
  78. enum class PublicAPI { D3D12 = 0, D3D11_47 = 1, D3D11_43 = 2 };
  79. #ifdef ADD_16_64_BIT_TYPES
  80. #define D3D_SVT_INT16 ((D3D_SHADER_VARIABLE_TYPE)58)
  81. #define D3D_SVT_UINT16 ((D3D_SHADER_VARIABLE_TYPE)59)
  82. #define D3D_SVT_FLOAT16 ((D3D_SHADER_VARIABLE_TYPE)60)
  83. #define D3D_SVT_INT64 ((D3D_SHADER_VARIABLE_TYPE)61)
  84. #define D3D_SVT_UINT64 ((D3D_SHADER_VARIABLE_TYPE)62)
  85. #endif // ADD_16_64_BIT_TYPES
  86. class DxilModuleReflection {
  87. public:
  88. hlsl::RDAT::DxilRuntimeData m_RDAT;
  89. LLVMContext Context;
  90. std::unique_ptr<Module> m_pModule; // Must come after LLVMContext, otherwise unique_ptr will over-delete.
  91. DxilModule *m_pDxilModule = nullptr;
  92. bool m_bUsageInMetadata = false;
  93. std::vector<std::unique_ptr<CShaderReflectionConstantBuffer>> m_CBs;
  94. std::vector<D3D12_SHADER_INPUT_BIND_DESC> m_Resources;
  95. std::vector<std::unique_ptr<CShaderReflectionType>> m_Types;
  96. // Key strings owned by CShaderReflectionConstantBuffer objects
  97. std::map<StringRef, UINT> m_CBsByName;
  98. // Due to the possibility of overlapping names between CB and other resources,
  99. // m_StructuredBufferCBsByName is the index into m_CBs corresponding to
  100. // StructuredBuffer resources, separately from CB resources.
  101. std::map<StringRef, UINT> m_StructuredBufferCBsByName;
  102. void CreateReflectionObjects();
  103. void CreateReflectionObjectForResource(DxilResourceBase *R);
  104. HRESULT LoadRDAT(const DxilPartHeader *pPart);
  105. HRESULT LoadModule(const DxilPartHeader *pPart);
  106. // Common code
  107. ID3D12ShaderReflectionConstantBuffer* _GetConstantBufferByIndex(UINT Index);
  108. ID3D12ShaderReflectionConstantBuffer* _GetConstantBufferByName(LPCSTR Name);
  109. HRESULT _GetResourceBindingDesc(UINT ResourceIndex,
  110. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc,
  111. PublicAPI api = PublicAPI::D3D12);
  112. ID3D12ShaderReflectionVariable* _GetVariableByName(LPCSTR Name);
  113. HRESULT _GetResourceBindingDescByName(LPCSTR Name,
  114. D3D12_SHADER_INPUT_BIND_DESC *pDesc,
  115. PublicAPI api = PublicAPI::D3D12);
  116. };
  117. class DxilShaderReflection : public DxilModuleReflection, public ID3D12ShaderReflection {
  118. private:
  119. DXC_MICROCOM_TM_REF_FIELDS()
  120. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_InputSignature;
  121. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_OutputSignature;
  122. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> m_PatchConstantSignature;
  123. std::vector<std::unique_ptr<char[]>> m_UpperCaseNames;
  124. D3D12_SHADER_DESC m_Desc = {};
  125. void SetCBufferUsage();
  126. void CreateReflectionObjectsForSignature(
  127. const DxilSignature &Sig,
  128. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> &Descs);
  129. LPCSTR CreateUpperCase(LPCSTR pValue);
  130. void MarkUsedSignatureElements();
  131. void InitDesc();
  132. public:
  133. PublicAPI m_PublicAPI;
  134. void SetPublicAPI(PublicAPI value) { m_PublicAPI = value; }
  135. static PublicAPI IIDToAPI(REFIID iid) {
  136. PublicAPI api = PublicAPI::D3D12;
  137. if (IsEqualIID(IID_ID3D11ShaderReflection_43, iid))
  138. api = PublicAPI::D3D11_43;
  139. else if (IsEqualIID(IID_ID3D11ShaderReflection_47, iid))
  140. api = PublicAPI::D3D11_47;
  141. return api;
  142. }
  143. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  144. DXC_MICROCOM_TM_CTOR(DxilShaderReflection)
  145. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  146. HRESULT hr = DoBasicQueryInterface<ID3D12ShaderReflection>(this, iid, ppvObject);
  147. if (hr == E_NOINTERFACE) {
  148. // ID3D11ShaderReflection is identical to ID3D12ShaderReflection, except
  149. // for some shorter data structures in some out parameters.
  150. PublicAPI api = IIDToAPI(iid);
  151. if (api == m_PublicAPI) {
  152. *ppvObject = (ID3D12ShaderReflection *)this;
  153. this->AddRef();
  154. hr = S_OK;
  155. }
  156. }
  157. return hr;
  158. }
  159. HRESULT Load(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart);
  160. // ID3D12ShaderReflection
  161. STDMETHODIMP GetDesc(THIS_ _Out_ D3D12_SHADER_DESC *pDesc);
  162. STDMETHODIMP_(ID3D12ShaderReflectionConstantBuffer*) GetConstantBufferByIndex(THIS_ _In_ UINT Index);
  163. STDMETHODIMP_(ID3D12ShaderReflectionConstantBuffer*) GetConstantBufferByName(THIS_ _In_ LPCSTR Name);
  164. STDMETHODIMP GetResourceBindingDesc(THIS_ _In_ UINT ResourceIndex,
  165. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc);
  166. STDMETHODIMP GetInputParameterDesc(THIS_ _In_ UINT ParameterIndex,
  167. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  168. STDMETHODIMP GetOutputParameterDesc(THIS_ _In_ UINT ParameterIndex,
  169. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  170. STDMETHODIMP GetPatchConstantParameterDesc(THIS_ _In_ UINT ParameterIndex,
  171. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc);
  172. STDMETHODIMP_(ID3D12ShaderReflectionVariable*) GetVariableByName(THIS_ _In_ LPCSTR Name);
  173. STDMETHODIMP GetResourceBindingDescByName(THIS_ _In_ LPCSTR Name,
  174. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc);
  175. STDMETHODIMP_(UINT) GetMovInstructionCount(THIS);
  176. STDMETHODIMP_(UINT) GetMovcInstructionCount(THIS);
  177. STDMETHODIMP_(UINT) GetConversionInstructionCount(THIS);
  178. STDMETHODIMP_(UINT) GetBitwiseInstructionCount(THIS);
  179. STDMETHODIMP_(D3D_PRIMITIVE) GetGSInputPrimitive(THIS);
  180. STDMETHODIMP_(BOOL) IsSampleFrequencyShader(THIS);
  181. STDMETHODIMP_(UINT) GetNumInterfaceSlots(THIS);
  182. STDMETHODIMP GetMinFeatureLevel(THIS_ _Out_ enum D3D_FEATURE_LEVEL* pLevel);
  183. STDMETHODIMP_(UINT) GetThreadGroupSize(THIS_
  184. _Out_opt_ UINT* pSizeX,
  185. _Out_opt_ UINT* pSizeY,
  186. _Out_opt_ UINT* pSizeZ);
  187. STDMETHODIMP_(UINT64) GetRequiresFlags(THIS);
  188. };
  189. class CFunctionReflection;
  190. class DxilLibraryReflection : public DxilModuleReflection, public ID3D12LibraryReflection {
  191. private:
  192. DXC_MICROCOM_TM_REF_FIELDS()
  193. // Storage, and function by name:
  194. typedef DenseMap<StringRef, std::unique_ptr<CFunctionReflection> > FunctionMap;
  195. typedef DenseMap<const Function*, CFunctionReflection*> FunctionsByPtr;
  196. FunctionMap m_FunctionMap;
  197. FunctionsByPtr m_FunctionsByPtr;
  198. // Enable indexing into functions in deterministic order:
  199. std::vector<CFunctionReflection*> m_FunctionVector;
  200. void AddResourceDependencies();
  201. void SetCBufferUsage();
  202. public:
  203. DXC_MICROCOM_TM_ADDREF_RELEASE_IMPL()
  204. DXC_MICROCOM_TM_CTOR(DxilLibraryReflection)
  205. HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void **ppvObject) {
  206. return DoBasicQueryInterface<ID3D12LibraryReflection>(this, iid, ppvObject);
  207. }
  208. HRESULT Load(const DxilPartHeader *pModulePart, const DxilPartHeader *pDXILPart);
  209. // ID3D12LibraryReflection
  210. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_LIBRARY_DESC * pDesc);
  211. STDMETHOD_(ID3D12FunctionReflection *, GetFunctionByIndex)(THIS_ _In_ INT FunctionIndex);
  212. };
  213. namespace hlsl {
  214. HRESULT CreateDxilShaderReflection(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject) {
  215. if (!ppvObject)
  216. return E_INVALIDARG;
  217. CComPtr<DxilShaderReflection> pReflection = DxilShaderReflection::Alloc(DxcGetThreadMallocNoRef());
  218. IFROOM(pReflection.p);
  219. PublicAPI api = DxilShaderReflection::IIDToAPI(iid);
  220. pReflection->SetPublicAPI(api);
  221. // pRDATPart to be used for transition.
  222. IFR(pReflection->Load(pModulePart, pRDATPart));
  223. IFR(pReflection.p->QueryInterface(iid, ppvObject));
  224. return S_OK;
  225. }
  226. HRESULT CreateDxilLibraryReflection(const DxilPartHeader *pModulePart, const DxilPartHeader *pRDATPart, REFIID iid, void **ppvObject) {
  227. if (!ppvObject)
  228. return E_INVALIDARG;
  229. CComPtr<DxilLibraryReflection> pReflection = DxilLibraryReflection::Alloc(DxcGetThreadMallocNoRef());
  230. IFROOM(pReflection.p);
  231. // pRDATPart used for resource usage per-function.
  232. IFR(pReflection->Load(pModulePart, pRDATPart));
  233. IFR(pReflection.p->QueryInterface(iid, ppvObject));
  234. return S_OK;
  235. }
  236. }
  237. _Use_decl_annotations_
  238. HRESULT DxilContainerReflection::Load(IDxcBlob *pContainer) {
  239. if (pContainer == nullptr) {
  240. m_container.Release();
  241. m_pHeader = nullptr;
  242. m_headerLen = 0;
  243. return S_OK;
  244. }
  245. CComPtr<IDxcBlob> pPDBContainer;
  246. try {
  247. DxcThreadMalloc DxcMalloc(m_pMalloc);
  248. CComPtr<IStream> pStream;
  249. IFR(hlsl::CreateReadOnlyBlobStream(pContainer, &pStream));
  250. if (SUCCEEDED(hlsl::pdb::LoadDataFromStream(m_pMalloc, pStream, &pPDBContainer))) {
  251. pContainer = pPDBContainer;
  252. }
  253. }
  254. CATCH_CPP_RETURN_HRESULT();
  255. uint32_t bufLen = pContainer->GetBufferSize();
  256. const DxilContainerHeader *pHeader =
  257. IsDxilContainerLike(pContainer->GetBufferPointer(), bufLen);
  258. if (pHeader == nullptr) {
  259. return E_INVALIDARG;
  260. }
  261. if (!IsValidDxilContainer(pHeader, bufLen)) {
  262. return E_INVALIDARG;
  263. }
  264. m_container = pContainer;
  265. m_headerLen = bufLen;
  266. m_pHeader = pHeader;
  267. return S_OK;
  268. }
  269. _Use_decl_annotations_
  270. HRESULT DxilContainerReflection::GetPartCount(UINT32 *pResult) {
  271. if (pResult == nullptr) return E_POINTER;
  272. if (!IsLoaded()) return E_NOT_VALID_STATE;
  273. *pResult = m_pHeader->PartCount;
  274. return S_OK;
  275. }
  276. _Use_decl_annotations_
  277. HRESULT DxilContainerReflection::GetPartKind(UINT32 idx, _Out_ UINT32 *pResult) {
  278. if (pResult == nullptr) return E_POINTER;
  279. if (!IsLoaded()) return E_NOT_VALID_STATE;
  280. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  281. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  282. *pResult = pPart->PartFourCC;
  283. return S_OK;
  284. }
  285. _Use_decl_annotations_
  286. HRESULT DxilContainerReflection::GetPartContent(UINT32 idx, _COM_Outptr_ IDxcBlob **ppResult) {
  287. if (ppResult == nullptr) return E_POINTER;
  288. *ppResult = nullptr;
  289. if (!IsLoaded()) return E_NOT_VALID_STATE;
  290. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  291. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  292. const char *pData = GetDxilPartData(pPart);
  293. uint32_t offset = (uint32_t)(pData - (char*)m_container->GetBufferPointer()); // Offset from the beginning.
  294. uint32_t length = pPart->PartSize;
  295. DxcThreadMalloc TM(m_pMalloc);
  296. return DxcCreateBlobFromBlob(m_container, offset, length, ppResult);
  297. }
  298. _Use_decl_annotations_
  299. HRESULT DxilContainerReflection::FindFirstPartKind(UINT32 kind, _Out_ UINT32 *pResult) {
  300. if (pResult == nullptr) return E_POINTER;
  301. *pResult = 0;
  302. if (!IsLoaded()) return E_NOT_VALID_STATE;
  303. DxilPartIterator it = std::find_if(begin(m_pHeader), end(m_pHeader), DxilPartIsType(kind));
  304. if (it == end(m_pHeader)) return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
  305. *pResult = it.index;
  306. return S_OK;
  307. }
  308. _Use_decl_annotations_
  309. HRESULT DxilContainerReflection::GetPartReflection(UINT32 idx, REFIID iid, void **ppvObject) {
  310. if (ppvObject == nullptr) return E_POINTER;
  311. *ppvObject = nullptr;
  312. if (!IsLoaded()) return E_NOT_VALID_STATE;
  313. if (idx >= m_pHeader->PartCount) return E_BOUNDS;
  314. const DxilPartHeader *pPart = GetDxilContainerPart(m_pHeader, idx);
  315. if (pPart->PartFourCC != DFCC_DXIL && pPart->PartFourCC != DFCC_ShaderDebugInfoDXIL &&
  316. pPart->PartFourCC != DFCC_ShaderStatistics) {
  317. return E_NOTIMPL;
  318. }
  319. // Use DFCC_ShaderStatistics for reflection instead of DXIL part, until switch
  320. // to using RDAT for reflection instead of module.
  321. const DxilPartHeader *pRDATPart = nullptr;
  322. for (idx = 0; idx < m_pHeader->PartCount; ++idx) {
  323. const DxilPartHeader *pPartTest = GetDxilContainerPart(m_pHeader, idx);
  324. if (pPartTest->PartFourCC == DFCC_RuntimeData) {
  325. pRDATPart = pPartTest;
  326. }
  327. if (pPart->PartFourCC != DFCC_ShaderStatistics) {
  328. if (pPartTest->PartFourCC == DFCC_ShaderStatistics) {
  329. const DxilProgramHeader *pProgramHeaderTest =
  330. reinterpret_cast<const DxilProgramHeader*>(GetDxilPartData(pPartTest));
  331. if (IsValidDxilProgramHeader(pProgramHeaderTest, pPartTest->PartSize)) {
  332. pPart = pPartTest;
  333. continue;
  334. }
  335. }
  336. }
  337. }
  338. const DxilProgramHeader *pProgramHeader =
  339. reinterpret_cast<const DxilProgramHeader*>(GetDxilPartData(pPart));
  340. if (!IsValidDxilProgramHeader(pProgramHeader, pPart->PartSize)) {
  341. return E_INVALIDARG;
  342. }
  343. DxcThreadMalloc TM(m_pMalloc);
  344. HRESULT hr = S_OK;
  345. DXIL::ShaderKind SK = GetVersionShaderType(pProgramHeader->ProgramVersion);
  346. if (SK == DXIL::ShaderKind::Library) {
  347. IFC(hlsl::CreateDxilLibraryReflection(pPart, pRDATPart, iid, ppvObject));
  348. } else {
  349. IFC(hlsl::CreateDxilShaderReflection(pPart, pRDATPart, iid, ppvObject));
  350. }
  351. Cleanup:
  352. return hr;
  353. }
  354. void hlsl::CreateDxcContainerReflection(IDxcContainerReflection **ppResult) {
  355. CComPtr<DxilContainerReflection> pReflection = DxilContainerReflection::Alloc(DxcGetThreadMallocNoRef());
  356. *ppResult = pReflection.Detach();
  357. if (*ppResult == nullptr) throw std::bad_alloc();
  358. }
  359. ///////////////////////////////////////////////////////////////////////////////
  360. // DxilShaderReflection implementation - helper objects. //
  361. class CShaderReflectionType;
  362. class CShaderReflectionVariable;
  363. class CShaderReflectionConstantBuffer;
  364. class CShaderReflection;
  365. struct D3D11_INTERNALSHADER_RESOURCE_DEF;
  366. class CShaderReflectionType : public ID3D12ShaderReflectionType
  367. {
  368. friend class CShaderReflectionConstantBuffer;
  369. protected:
  370. D3D12_SHADER_TYPE_DESC m_Desc;
  371. UINT m_SizeInCBuffer;
  372. std::string m_Name;
  373. std::vector<StringRef> m_MemberNames;
  374. std::vector<CShaderReflectionType*> m_MemberTypes;
  375. CShaderReflectionType* m_pSubType;
  376. CShaderReflectionType* m_pBaseClass;
  377. std::vector<CShaderReflectionType*> m_Interfaces;
  378. ULONG_PTR m_Identity;
  379. public:
  380. // Internal
  381. HRESULT InitializeEmpty();
  382. HRESULT Initialize(
  383. DxilModule &M,
  384. llvm::Type *type,
  385. DxilFieldAnnotation &typeAnnotation,
  386. unsigned int baseOffset,
  387. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  388. bool isCBuffer);
  389. // ID3D12ShaderReflectionType
  390. STDMETHOD(GetDesc)(D3D12_SHADER_TYPE_DESC *pDesc);
  391. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(UINT Index);
  392. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(LPCSTR Name);
  393. STDMETHOD_(LPCSTR, GetMemberTypeName)(UINT Index);
  394. STDMETHOD(IsEqual)(THIS_ ID3D12ShaderReflectionType* pType);
  395. STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS);
  396. STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS);
  397. STDMETHOD_(UINT, GetNumInterfaces)(THIS);
  398. STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ UINT uIndex);
  399. STDMETHOD(IsOfType)(THIS_ ID3D12ShaderReflectionType* pType);
  400. STDMETHOD(ImplementsInterface)(THIS_ ID3D12ShaderReflectionType* pBase);
  401. bool CheckEqual(_In_ CShaderReflectionType *pOther) {
  402. return m_Identity == pOther->m_Identity;
  403. }
  404. UINT GetCBufferSize() { return m_SizeInCBuffer; }
  405. };
  406. class CShaderReflectionVariable : public ID3D12ShaderReflectionVariable
  407. {
  408. protected:
  409. D3D12_SHADER_VARIABLE_DESC m_Desc;
  410. CShaderReflectionType *m_pType;
  411. CShaderReflectionConstantBuffer *m_pBuffer;
  412. BYTE *m_pDefaultValue;
  413. public:
  414. void Initialize(CShaderReflectionConstantBuffer *pBuffer,
  415. D3D12_SHADER_VARIABLE_DESC *pDesc,
  416. CShaderReflectionType *pType, BYTE *pDefaultValue);
  417. LPCSTR GetName() { return m_Desc.Name; }
  418. // ID3D12ShaderReflectionVariable
  419. STDMETHOD(GetDesc)(D3D12_SHADER_VARIABLE_DESC *pDesc);
  420. STDMETHOD_(ID3D12ShaderReflectionType*, GetType)();
  421. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)();
  422. STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ UINT uArrayIndex);
  423. };
  424. class CShaderReflectionConstantBuffer : public ID3D12ShaderReflectionConstantBuffer
  425. {
  426. protected:
  427. D3D12_SHADER_BUFFER_DESC m_Desc;
  428. std::vector<CShaderReflectionVariable> m_Variables;
  429. // For StructuredBuffer arrays, Name will have [0] appended for each dimension to match fxc behavior.
  430. std::string m_ReflectionName;
  431. public:
  432. CShaderReflectionConstantBuffer() = default;
  433. CShaderReflectionConstantBuffer(CShaderReflectionConstantBuffer &&other) {
  434. m_Desc = other.m_Desc;
  435. std::swap(m_Variables, other.m_Variables);
  436. }
  437. void Initialize(DxilModule &M,
  438. DxilCBuffer &CB,
  439. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  440. bool bUsageInMetadata);
  441. void InitializeStructuredBuffer(DxilModule &M,
  442. DxilResource &R,
  443. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes);
  444. void InitializeTBuffer(DxilModule &M,
  445. DxilResource &R,
  446. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  447. bool bUsageInMetadata);
  448. LPCSTR GetName() { return m_Desc.Name; }
  449. // ID3D12ShaderReflectionConstantBuffer
  450. STDMETHOD(GetDesc)(D3D12_SHADER_BUFFER_DESC *pDesc);
  451. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(UINT Index);
  452. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(LPCSTR Name);
  453. };
  454. // Invalid type sentinel definitions
  455. class CInvalidSRType;
  456. class CInvalidSRVariable;
  457. class CInvalidSRConstantBuffer;
  458. class CInvalidSRLibraryFunction;
  459. class CInvalidSRFunctionParameter;
  460. class CInvalidSRType : public ID3D12ShaderReflectionType {
  461. STDMETHOD(GetDesc)(D3D12_SHADER_TYPE_DESC *pDesc) { return E_FAIL; }
  462. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByIndex)(UINT Index);
  463. STDMETHOD_(ID3D12ShaderReflectionType*, GetMemberTypeByName)(LPCSTR Name);
  464. STDMETHOD_(LPCSTR, GetMemberTypeName)(UINT Index) { return "$Invalid"; }
  465. STDMETHOD(IsEqual)(THIS_ ID3D12ShaderReflectionType* pType) { return E_FAIL; }
  466. STDMETHOD_(ID3D12ShaderReflectionType*, GetSubType)(THIS);
  467. STDMETHOD_(ID3D12ShaderReflectionType*, GetBaseClass)(THIS);
  468. STDMETHOD_(UINT, GetNumInterfaces)(THIS) { return 0; }
  469. STDMETHOD_(ID3D12ShaderReflectionType*, GetInterfaceByIndex)(THIS_ UINT uIndex);
  470. STDMETHOD(IsOfType)(THIS_ ID3D12ShaderReflectionType* pType) { return E_FAIL; }
  471. STDMETHOD(ImplementsInterface)(THIS_ ID3D12ShaderReflectionType* pBase) { return E_FAIL; }
  472. };
  473. static CInvalidSRType g_InvalidSRType;
  474. ID3D12ShaderReflectionType* CInvalidSRType::GetMemberTypeByIndex(UINT) { return &g_InvalidSRType; }
  475. ID3D12ShaderReflectionType* CInvalidSRType::GetMemberTypeByName(LPCSTR) { return &g_InvalidSRType; }
  476. ID3D12ShaderReflectionType* CInvalidSRType::GetSubType() { return &g_InvalidSRType; }
  477. ID3D12ShaderReflectionType* CInvalidSRType::GetBaseClass() { return &g_InvalidSRType; }
  478. ID3D12ShaderReflectionType* CInvalidSRType::GetInterfaceByIndex(UINT) { return &g_InvalidSRType; }
  479. class CInvalidSRVariable : public ID3D12ShaderReflectionVariable {
  480. STDMETHOD(GetDesc)(D3D12_SHADER_VARIABLE_DESC *pDesc) { return E_FAIL; }
  481. STDMETHOD_(ID3D12ShaderReflectionType*, GetType)() { return &g_InvalidSRType; }
  482. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer*, GetBuffer)();
  483. STDMETHOD_(UINT, GetInterfaceSlot)(THIS_ UINT uIndex) { return UINT_MAX; }
  484. };
  485. static CInvalidSRVariable g_InvalidSRVariable;
  486. class CInvalidSRConstantBuffer : public ID3D12ShaderReflectionConstantBuffer {
  487. STDMETHOD(GetDesc)(D3D12_SHADER_BUFFER_DESC *pDesc) { return E_FAIL; }
  488. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByIndex)(UINT Index) { return &g_InvalidSRVariable; }
  489. STDMETHOD_(ID3D12ShaderReflectionVariable*, GetVariableByName)(LPCSTR Name) { return &g_InvalidSRVariable; }
  490. };
  491. static CInvalidSRConstantBuffer g_InvalidSRConstantBuffer;
  492. class CInvalidFunctionParameter : public ID3D12FunctionParameterReflection {
  493. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_PARAMETER_DESC * pDesc) { return E_FAIL; }
  494. };
  495. CInvalidFunctionParameter g_InvalidFunctionParameter;
  496. class CInvalidFunction : public ID3D12FunctionReflection {
  497. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc) { return E_FAIL; }
  498. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex) { return &g_InvalidSRConstantBuffer; }
  499. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name) { return &g_InvalidSRConstantBuffer; }
  500. STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex,
  501. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) { return E_FAIL; }
  502. STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name) { return nullptr; }
  503. STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name,
  504. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc) { return E_FAIL; }
  505. // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value.
  506. STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) { return &g_InvalidFunctionParameter; }
  507. };
  508. CInvalidFunction g_InvalidFunction;
  509. void CShaderReflectionVariable::Initialize(
  510. CShaderReflectionConstantBuffer *pBuffer, D3D12_SHADER_VARIABLE_DESC *pDesc,
  511. CShaderReflectionType *pType, BYTE *pDefaultValue) {
  512. m_pBuffer = pBuffer;
  513. memcpy(&m_Desc, pDesc, sizeof(m_Desc));
  514. m_pType = pType;
  515. m_pDefaultValue = pDefaultValue;
  516. }
  517. HRESULT CShaderReflectionVariable::GetDesc(D3D12_SHADER_VARIABLE_DESC *pDesc) {
  518. if (!pDesc) return E_POINTER;
  519. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  520. return S_OK;
  521. }
  522. ID3D12ShaderReflectionType *CShaderReflectionVariable::GetType() {
  523. return m_pType;
  524. }
  525. ID3D12ShaderReflectionConstantBuffer *CShaderReflectionVariable::GetBuffer() {
  526. return m_pBuffer;
  527. }
  528. UINT CShaderReflectionVariable::GetInterfaceSlot(UINT uArrayIndex) {
  529. return UINT_MAX;
  530. }
  531. ID3D12ShaderReflectionConstantBuffer *CInvalidSRVariable::GetBuffer() {
  532. return &g_InvalidSRConstantBuffer;
  533. }
  534. STDMETHODIMP CShaderReflectionType::GetDesc(D3D12_SHADER_TYPE_DESC *pDesc)
  535. {
  536. if (!pDesc) return E_POINTER;
  537. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  538. return S_OK;
  539. }
  540. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetMemberTypeByIndex(UINT Index)
  541. {
  542. if (Index >= m_MemberTypes.size()) {
  543. return &g_InvalidSRType;
  544. }
  545. return m_MemberTypes[Index];
  546. }
  547. STDMETHODIMP_(LPCSTR) CShaderReflectionType::GetMemberTypeName(UINT Index)
  548. {
  549. if (Index >= m_MemberTypes.size()) {
  550. return nullptr;
  551. }
  552. return (LPCSTR) m_MemberNames[Index].bytes_begin();
  553. }
  554. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetMemberTypeByName(LPCSTR Name)
  555. {
  556. UINT memberCount = m_Desc.Members;
  557. for( UINT mm = 0; mm < memberCount; ++mm ) {
  558. if( m_MemberNames[mm] == Name ) {
  559. return m_MemberTypes[mm];
  560. }
  561. }
  562. return nullptr;
  563. }
  564. STDMETHODIMP CShaderReflectionType::IsEqual(THIS_ ID3D12ShaderReflectionType* pType)
  565. {
  566. // TODO: implement this check, if users actually depend on it
  567. return S_FALSE;
  568. }
  569. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetSubType(THIS)
  570. {
  571. // TODO: implement `class`-related features, if requested
  572. return nullptr;
  573. }
  574. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetBaseClass(THIS)
  575. {
  576. // TODO: implement `class`-related features, if requested
  577. return nullptr;
  578. }
  579. STDMETHODIMP_(UINT) CShaderReflectionType::GetNumInterfaces(THIS)
  580. {
  581. // HLSL interfaces have been deprecated
  582. return 0;
  583. }
  584. STDMETHODIMP_(ID3D12ShaderReflectionType*) CShaderReflectionType::GetInterfaceByIndex(THIS_ UINT uIndex)
  585. {
  586. // HLSL interfaces have been deprecated
  587. return nullptr;
  588. }
  589. STDMETHODIMP CShaderReflectionType::IsOfType(THIS_ ID3D12ShaderReflectionType* pType)
  590. {
  591. // TODO: implement `class`-related features, if requested
  592. return S_FALSE;
  593. }
  594. STDMETHODIMP CShaderReflectionType::ImplementsInterface(THIS_ ID3D12ShaderReflectionType* pBase)
  595. {
  596. // HLSL interfaces have been deprecated
  597. return S_FALSE;
  598. }
  599. // Helper routine for types that don't have an obvious mapping
  600. // to the existing shader reflection interface.
  601. static bool ProcessUnhandledObjectType(
  602. llvm::StructType *structType,
  603. D3D_SHADER_VARIABLE_TYPE *outObjectType)
  604. {
  605. // Don't actually make this a hard error, but instead report the problem using a suitable debug message.
  606. #ifdef DBG
  607. OutputDebugFormatA("DxilContainerReflection.cpp: error: unhandled object type '%s'.\n", structType->getName().str().c_str());
  608. #endif
  609. *outObjectType = D3D_SVT_VOID;
  610. return true;
  611. }
  612. // Helper routine to try to detect if a type represents an HLSL "object" type
  613. // (a texture, sampler, buffer, etc.), and to extract the coresponding shader
  614. // reflection type.
  615. static bool TryToDetectObjectType(
  616. llvm::StructType *structType,
  617. D3D_SHADER_VARIABLE_TYPE *outObjectType)
  618. {
  619. // Note: This logic is largely duplicated from `dxilutil::IsHLSLObjectType`
  620. // with the addition of returning the appropriate reflection type tag.
  621. //
  622. // That logic looks error-prone, since it relies on string tests against
  623. // type names, including cases that just test against a prefix.
  624. // This code doesn't try to be any more robust.
  625. StringRef name = structType->getName();
  626. if(name.startswith("dx.types.wave_t") )
  627. {
  628. return ProcessUnhandledObjectType(structType, outObjectType);
  629. }
  630. // Strip off some prefixes we are likely to see.
  631. name = name.ltrim("class.");
  632. name = name.ltrim("struct.");
  633. // Slice types occur as intermediates (they aren not objects)
  634. if(name.endswith("_slice_type")) { return false; }
  635. // We might check for an exact name match, or a prefix match
  636. #define EXACT_MATCH(NAME, TAG) \
  637. else if(name == #NAME) do { *outObjectType = TAG; return true; } while(0)
  638. #define PREFIX_MATCH(NAME, TAG) \
  639. else if(name.startswith(#NAME)) do { *outObjectType = TAG; return true; } while(0)
  640. if(0) {}
  641. EXACT_MATCH(SamplerState, D3D_SVT_SAMPLER);
  642. EXACT_MATCH(SamplerComparisonState, D3D_SVT_SAMPLER);
  643. // Note: GS output stream types are supported in the reflection interface.
  644. else if(name.startswith("TriangleStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  645. else if(name.startswith("PointStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  646. else if(name.startswith("LineStream")) { return ProcessUnhandledObjectType(structType, outObjectType); }
  647. PREFIX_MATCH(AppendStructuredBuffer, D3D_SVT_APPEND_STRUCTURED_BUFFER);
  648. PREFIX_MATCH(ConsumeStructuredBuffer, D3D_SVT_CONSUME_STRUCTURED_BUFFER);
  649. PREFIX_MATCH(ConstantBuffer, D3D_SVT_CBUFFER);
  650. // Note: the `HLModule` code does this trick to avoid checking more names
  651. // than it has to, but it doesn't seem 100% correct to do this.
  652. // TODO: consider just listing the `RasterizerOrdered` cases explicitly,
  653. // just as we do for the `RW` cases already.
  654. name = name.ltrim("RasterizerOrdered");
  655. if(0) {}
  656. EXACT_MATCH(ByteAddressBuffer, D3D_SVT_BYTEADDRESS_BUFFER);
  657. EXACT_MATCH(RWByteAddressBuffer, D3D_SVT_RWBYTEADDRESS_BUFFER);
  658. PREFIX_MATCH(Buffer, D3D_SVT_BUFFER);
  659. PREFIX_MATCH(RWBuffer, D3D_SVT_RWBUFFER);
  660. PREFIX_MATCH(StructuredBuffer, D3D_SVT_STRUCTURED_BUFFER);
  661. PREFIX_MATCH(RWStructuredBuffer, D3D_SVT_RWSTRUCTURED_BUFFER);
  662. PREFIX_MATCH(Texture1D, D3D_SVT_TEXTURE1D);
  663. PREFIX_MATCH(RWTexture1D, D3D_SVT_RWTEXTURE1D);
  664. PREFIX_MATCH(Texture1DArray, D3D_SVT_TEXTURE1DARRAY);
  665. PREFIX_MATCH(RWTexture1DArray, D3D_SVT_RWTEXTURE1DARRAY);
  666. PREFIX_MATCH(Texture2D, D3D_SVT_TEXTURE2D);
  667. PREFIX_MATCH(RWTexture2D, D3D_SVT_RWTEXTURE2D);
  668. PREFIX_MATCH(Texture2DArray, D3D_SVT_TEXTURE2DARRAY);
  669. PREFIX_MATCH(RWTexture2DArray, D3D_SVT_RWTEXTURE2DARRAY);
  670. PREFIX_MATCH(Texture3D, D3D_SVT_TEXTURE3D);
  671. PREFIX_MATCH(RWTexture3D, D3D_SVT_RWTEXTURE3D);
  672. PREFIX_MATCH(TextureCube, D3D_SVT_TEXTURECUBE);
  673. PREFIX_MATCH(TextureCubeArray, D3D_SVT_TEXTURECUBEARRAY);
  674. PREFIX_MATCH(Texture2DMS, D3D_SVT_TEXTURE2DMS);
  675. PREFIX_MATCH(Texture2DMSArray, D3D_SVT_TEXTURE2DMSARRAY);
  676. #undef EXACT_MATCH
  677. #undef PREFIX_MATCH
  678. // Default: not an object type
  679. return false;
  680. }
  681. // Helper to determine if an LLVM type represents an HLSL
  682. // object type (uses the `TryToDetectObjectType()` function
  683. // defined previously).
  684. static bool IsObjectType(
  685. llvm::Type* inType)
  686. {
  687. llvm::Type* type = inType;
  688. while(type->isArrayTy())
  689. {
  690. type = type->getArrayElementType();
  691. }
  692. llvm::StructType* structType = dyn_cast<StructType>(type);
  693. if(!structType)
  694. return false;
  695. D3D_SHADER_VARIABLE_TYPE ignored;
  696. return TryToDetectObjectType(structType, &ignored);
  697. }
  698. HRESULT CShaderReflectionType::InitializeEmpty()
  699. {
  700. ZeroMemory(&m_Desc, sizeof(m_Desc));
  701. return S_OK;
  702. }
  703. // Main logic for translating an LLVM type and associated
  704. // annotations into a D3D shader reflection type.
  705. HRESULT CShaderReflectionType::Initialize(
  706. DxilModule &M,
  707. llvm::Type *inType,
  708. DxilFieldAnnotation &typeAnnotation,
  709. unsigned int baseOffset,
  710. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  711. bool isCBuffer)
  712. {
  713. DXASSERT_NOMSG(inType);
  714. // Set a bunch of fields to default values, to avoid duplication.
  715. m_Desc.Rows = 0;
  716. m_Desc.Columns = 0;
  717. m_Desc.Elements = 0;
  718. m_Desc.Members = 0;
  719. m_SizeInCBuffer = 0;
  720. // Used for calculating size later
  721. unsigned cbRows = 1;
  722. unsigned cbCols = 1;
  723. unsigned cbCompSize = 4; // or 8 for 64-bit types.
  724. unsigned cbRowStride = 16; // or 32 if 64-bit and cols > 2.
  725. if (isCBuffer) {
  726. // Extract offset relative to parent.
  727. // Note: the `baseOffset` is used in the case where the type in
  728. // question is a field in a constant buffer, since then both the
  729. // field and the variable store the same offset information, and
  730. // we need to zero out the value in the type to avoid the user
  731. // of the reflection interface seeing 2x the correct value.
  732. m_Desc.Offset = typeAnnotation.GetCBufferOffset() - baseOffset;
  733. } else {
  734. m_Desc.Offset = baseOffset;
  735. }
  736. // Arrays don't seem to be represented directly in the reflection
  737. // data, but only as the `Elements` field being non-zero.
  738. // We "unwrap" any array type here, and then proceed to look
  739. // at the element type.
  740. llvm::Type* type = inType;
  741. while(type->isArrayTy())
  742. {
  743. llvm::Type* elementType = type->getArrayElementType();
  744. // Note: At this point an HLSL matrix type may appear as an ordinary
  745. // array (not wrapped in a `struct`), so `dxilutil::IsHLSLMatrixType()`
  746. // is not sufficient. Instead we need to check the field annotation.
  747. //
  748. // We might have an array of matrices, though, so we only exit if
  749. // the field annotation says we have a matrix, and we've bottomed
  750. // out at one array level, since matrix will be in the format:
  751. // [rows x <cols x float>]
  752. //
  753. // This is in storage orientation, so rows/cols are swapped
  754. // when the matrix is column_major.
  755. //
  756. // However, when the matrix has a row size of 1 in storage orientation,
  757. // this array dimension appears to be missing.
  758. // To properly count the array dimensions for this case,
  759. // we must not break out of the loop one array early when rows == 1.
  760. if(typeAnnotation.HasMatrixAnnotation() && !elementType->isArrayTy() &&
  761. !HLMatrixType::isa(elementType)){
  762. const DxilMatrixAnnotation &mat = typeAnnotation.GetMatrixAnnotation();
  763. unsigned rows = mat.Orientation == MatrixOrientation::RowMajor ?
  764. mat.Rows : mat.Cols;
  765. // when rows == 1, in storage orientation, the row array is missing.
  766. if (rows > 1)
  767. break;
  768. }
  769. // Non-array types should have `Elements` be zero, so as soon as we
  770. // find that we have our first real array (not a matrix), we initialize `Elements`
  771. if(!m_Desc.Elements) m_Desc.Elements = 1;
  772. // It isn't clear what is the desired behavior for multi-dimensional arrays,
  773. // but for now we do the expedient thing of multiplying out all their
  774. // dimensions.
  775. m_Desc.Elements *= type->getArrayNumElements();
  776. type = elementType;
  777. }
  778. // Default to a scalar type, just to avoid some duplication later.
  779. m_Desc.Class = D3D_SVC_SCALAR;
  780. // Look at the annotation to try to determine the basic type of value.
  781. //
  782. // Note that DXIL supports some types that don't currently have equivalents
  783. // in the reflection interface, so we try to muddle through here.
  784. bool bMinPrec = M.GetUseMinPrecision();
  785. D3D_SHADER_VARIABLE_TYPE componentType = D3D_SVT_VOID;
  786. switch(typeAnnotation.GetCompType().GetKind())
  787. {
  788. case hlsl::DXIL::ComponentType::Invalid:
  789. break;
  790. case hlsl::DXIL::ComponentType::I1:
  791. componentType = D3D_SVT_BOOL;
  792. m_Name = "bool";
  793. break;
  794. case hlsl::DXIL::ComponentType::I16:
  795. if (bMinPrec) {
  796. componentType = D3D_SVT_MIN16INT;
  797. m_Name = "min16int";
  798. } else {
  799. componentType = D3D_SVT_INT16;
  800. m_Name = "int16_t";
  801. cbCompSize = 2;
  802. }
  803. break;
  804. case hlsl::DXIL::ComponentType::U16:
  805. if (bMinPrec) {
  806. componentType = D3D_SVT_MIN16UINT;
  807. m_Name = "min16uint";
  808. } else {
  809. componentType = D3D_SVT_UINT16;
  810. m_Name = "uint16_t";
  811. cbCompSize = 2;
  812. }
  813. break;
  814. case hlsl::DXIL::ComponentType::I64:
  815. componentType = D3D_SVT_INT64;
  816. m_Name = "int64_t";
  817. cbCompSize = 8;
  818. break;
  819. case hlsl::DXIL::ComponentType::I32:
  820. componentType = D3D_SVT_INT;
  821. m_Name = "int";
  822. break;
  823. case hlsl::DXIL::ComponentType::U64:
  824. componentType = D3D_SVT_UINT64;
  825. m_Name = "uint64_t";
  826. cbCompSize = 8;
  827. break;
  828. case hlsl::DXIL::ComponentType::U32:
  829. componentType = D3D_SVT_UINT;
  830. m_Name = "uint";
  831. break;
  832. case hlsl::DXIL::ComponentType::F16:
  833. case hlsl::DXIL::ComponentType::SNormF16:
  834. case hlsl::DXIL::ComponentType::UNormF16:
  835. if (bMinPrec) {
  836. componentType = D3D_SVT_MIN16FLOAT;
  837. m_Name = "min16float";
  838. } else {
  839. componentType = D3D_SVT_FLOAT16;
  840. m_Name = "float16_t";
  841. cbCompSize = 2;
  842. }
  843. break;
  844. case hlsl::DXIL::ComponentType::F32:
  845. case hlsl::DXIL::ComponentType::SNormF32:
  846. case hlsl::DXIL::ComponentType::UNormF32:
  847. componentType = D3D_SVT_FLOAT;
  848. m_Name = "float";
  849. break;
  850. case hlsl::DXIL::ComponentType::F64:
  851. case hlsl::DXIL::ComponentType::SNormF64:
  852. case hlsl::DXIL::ComponentType::UNormF64:
  853. cbCompSize = 8;
  854. componentType = D3D_SVT_DOUBLE;
  855. m_Name = "double";
  856. break;
  857. default:
  858. #ifdef DBG
  859. OutputDebugStringA("DxilContainerReflection.cpp: error: unknown component type\n");
  860. #endif
  861. break;
  862. }
  863. m_Desc.Type = componentType;
  864. // A matrix type is encoded as a vector type, plus annotations, so we
  865. // need to check for this case before other vector cases.
  866. if(typeAnnotation.HasMatrixAnnotation())
  867. {
  868. // We can extract the details from the annotation.
  869. DxilMatrixAnnotation const& matrixAnnotation = typeAnnotation.GetMatrixAnnotation();
  870. switch(matrixAnnotation.Orientation)
  871. {
  872. default:
  873. #ifdef DBG
  874. OutputDebugStringA("DxilContainerReflection.cpp: error: unknown matrix orientation\n");
  875. #endif
  876. // Note: column-major layout is the default
  877. case hlsl::MatrixOrientation::Undefined:
  878. case hlsl::MatrixOrientation::ColumnMajor:
  879. m_Desc.Class = D3D_SVC_MATRIX_COLUMNS;
  880. break;
  881. case hlsl::MatrixOrientation::RowMajor:
  882. m_Desc.Class = D3D_SVC_MATRIX_ROWS;
  883. break;
  884. }
  885. m_Desc.Rows = matrixAnnotation.Rows;
  886. m_Desc.Columns = matrixAnnotation.Cols;
  887. m_Name += std::to_string(matrixAnnotation.Rows) + "x" + std::to_string(matrixAnnotation.Cols);
  888. cbRows = m_Desc.Rows;
  889. cbCols = m_Desc.Columns;
  890. if (m_Desc.Class == D3D_SVC_MATRIX_COLUMNS) {
  891. std::swap(cbRows, cbCols);
  892. }
  893. }
  894. else if( type->isVectorTy() )
  895. {
  896. // We assume that LLVM vectors either represent matrices (handled above)
  897. // or HLSL vectors.
  898. //
  899. // Note: the reflection interface encodes an N-vector as if it had 1 row
  900. // and N columns.
  901. m_Desc.Class = D3D_SVC_VECTOR;
  902. m_Desc.Rows = 1;
  903. m_Desc.Columns = type->getVectorNumElements();
  904. m_Name += std::to_string(type->getVectorNumElements());
  905. cbRows = m_Desc.Rows;
  906. cbCols = m_Desc.Columns;
  907. }
  908. else if( type->isStructTy() )
  909. {
  910. // A struct type might be an ordinary user-defined `struct`,
  911. // or one of the builtin in HLSL "object" types.
  912. StructType *structType = cast<StructType>(type);
  913. const StructLayout *structLayout = isCBuffer ? nullptr :
  914. M.GetModule()->getDataLayout().getStructLayout(structType);
  915. // We use our function to try to detect an object type
  916. // based on its name.
  917. if(TryToDetectObjectType(structType, &m_Desc.Type))
  918. {
  919. m_Desc.Class = D3D_SVC_OBJECT;
  920. }
  921. else
  922. {
  923. // Otherwise we have a struct and need to recurse on its fields.
  924. m_Desc.Class = D3D_SVC_STRUCT;
  925. m_Desc.Rows = 1;
  926. // Try to "clean" the type name for use in reflection data
  927. llvm::StringRef name = structType->getName();
  928. name = name.ltrim("dx.alignment.legacy.");
  929. name = name.ltrim("struct.");
  930. m_Name = name;
  931. // Fields may have annotations, and we need to look at these
  932. // in order to decode their types properly.
  933. DxilTypeSystem &typeSys = M.GetTypeSystem();
  934. DxilStructAnnotation *structAnnotation = typeSys.GetStructAnnotation(structType);
  935. // There is no annotation for empty structs
  936. unsigned int fieldCount = 0;
  937. if (structAnnotation)
  938. fieldCount = type->getStructNumElements();
  939. // The DXBC reflection info computes `Columns` for a
  940. // `struct` type from the fields (see below)
  941. UINT columnCounter = 0;
  942. CShaderReflectionType *fieldReflectionType = nullptr;
  943. for(unsigned int ff = 0; ff < fieldCount; ++ff)
  944. {
  945. DxilFieldAnnotation& fieldAnnotation = structAnnotation->GetFieldAnnotation(ff);
  946. llvm::Type* fieldType = structType->getStructElementType(ff);
  947. // Skip fields with object types, since these are not part of constant buffers,
  948. // and are not allowed in other buffer types.
  949. if( IsObjectType(fieldType) )
  950. {
  951. continue;
  952. }
  953. fieldReflectionType = new CShaderReflectionType();
  954. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(fieldReflectionType));
  955. unsigned int elementOffset = structLayout ? (unsigned int)structLayout->getElementOffset(ff) : 0;
  956. fieldReflectionType->Initialize(M, fieldType, fieldAnnotation, elementOffset, allTypes, isCBuffer);
  957. m_MemberTypes.push_back(fieldReflectionType);
  958. m_MemberNames.push_back(fieldAnnotation.GetFieldName().c_str());
  959. // Effectively, we want to add one to `Columns` for every scalar nested recursively
  960. // inside this `struct` type (ignoring objects, which we filtered above). We should
  961. // be able to compute this as the product of the `Columns`, `Rows` and `Elements`
  962. // of each field, with the caveat that some of these may be zero, but shoud be
  963. // treated as one.
  964. columnCounter +=
  965. (fieldReflectionType->m_Desc.Columns ? fieldReflectionType->m_Desc.Columns : 1)
  966. * (fieldReflectionType->m_Desc.Rows ? fieldReflectionType->m_Desc.Rows : 1)
  967. * (fieldReflectionType->m_Desc.Elements ? fieldReflectionType->m_Desc.Elements : 1);
  968. }
  969. m_Desc.Columns = columnCounter;
  970. if (fieldReflectionType) {
  971. // Set our size based on the last fields offset + size:
  972. m_SizeInCBuffer = fieldReflectionType->m_Desc.Offset + fieldReflectionType->m_SizeInCBuffer;
  973. if (m_Desc.Elements > 1) {
  974. unsigned alignedSize = ((m_SizeInCBuffer + 15) & ~0xF);
  975. m_SizeInCBuffer += (m_Desc.Elements - 1) * alignedSize;
  976. }
  977. }
  978. // Because we might have skipped fields during enumeration,
  979. // the `Members` count in the description might not be the same
  980. // as the field count of the original LLVM type.
  981. m_Desc.Members = m_MemberTypes.size();
  982. }
  983. }
  984. else if( type->isPointerTy() )
  985. {
  986. #ifdef DBG
  987. OutputDebugStringA("DxilContainerReflection.cpp: error: cannot reflect pointer type\n");
  988. #endif
  989. }
  990. else if( type->isVoidTy() )
  991. {
  992. // Name for `void` wasn't handle in the component-type `switch` above
  993. m_Name = "void";
  994. m_Desc.Class = D3D_SVC_SCALAR;
  995. m_Desc.Rows = 1;
  996. m_Desc.Columns = 1;
  997. }
  998. else
  999. {
  1000. // Assume we have a scalar at this point.
  1001. m_Desc.Class = D3D_SVC_SCALAR;
  1002. m_Desc.Rows = 1;
  1003. m_Desc.Columns = 1;
  1004. // Special-case naming
  1005. switch(m_Desc.Type)
  1006. {
  1007. default:
  1008. break;
  1009. case D3D_SVT_UINT:
  1010. // Scalar `uint` gets reflected as `dword`, while vectors/matrices use `uint`...
  1011. m_Name = "dword";
  1012. break;
  1013. }
  1014. cbRows = 1;
  1015. cbCols = 1;
  1016. }
  1017. // TODO: are there other cases to be handled?
  1018. // Compute our cbuffer size for member reflection
  1019. switch (m_Desc.Class) {
  1020. case D3D_SVC_SCALAR:
  1021. case D3D_SVC_MATRIX_COLUMNS:
  1022. case D3D_SVC_MATRIX_ROWS:
  1023. case D3D_SVC_VECTOR:
  1024. if (m_Desc.Elements > 1)
  1025. cbRows = cbRows * m_Desc.Elements;
  1026. if (cbCompSize > 4 && cbCols > 2)
  1027. cbRowStride = 32;
  1028. m_SizeInCBuffer = cbRowStride * (cbRows - 1) + cbCompSize * cbCols;
  1029. break;
  1030. }
  1031. m_Desc.Name = m_Name.c_str();
  1032. return S_OK;
  1033. }
  1034. void CShaderReflectionConstantBuffer::Initialize(
  1035. DxilModule &M,
  1036. DxilCBuffer &CB,
  1037. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  1038. bool bUsageInMetadata) {
  1039. ZeroMemory(&m_Desc, sizeof(m_Desc));
  1040. m_ReflectionName = CB.GetGlobalName();
  1041. m_Desc.Name = m_ReflectionName.c_str();
  1042. m_Desc.Size = CB.GetSize();
  1043. m_Desc.Size = (m_Desc.Size + 0x0f) & ~(0x0f); // Round up to 16 bytes for reflection.
  1044. m_Desc.Type = D3D_CT_CBUFFER;
  1045. m_Desc.uFlags = 0;
  1046. // For ConstantBuffer<> buf[2], the array size is in Resource binding count
  1047. // part.
  1048. Type *Ty = dxilutil::StripArrayTypes(
  1049. CB.GetHLSLType()->getPointerElementType());
  1050. DxilTypeSystem &typeSys = M.GetTypeSystem();
  1051. StructType *ST = cast<StructType>(Ty);
  1052. DxilStructAnnotation *annotation =
  1053. typeSys.GetStructAnnotation(cast<StructType>(ST));
  1054. // Dxil from dxbc doesn't have annotation.
  1055. if (!annotation)
  1056. return;
  1057. m_Desc.Variables = ST->getNumContainedTypes();
  1058. if (CB.GetRangeSize() > 1) {
  1059. DXASSERT(m_Desc.Variables == 1, "otherwise, assumption is wrong");
  1060. }
  1061. // If only one member, it's used if it's here.
  1062. bool bAllUsed = ST->getNumContainedTypes() < 2;
  1063. bAllUsed |= !bUsageInMetadata; // Will update in SetCBufferUsage.
  1064. for (unsigned i = 0; i < ST->getNumContainedTypes(); ++i) {
  1065. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  1066. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1067. ZeroMemory(&VarDesc, sizeof(VarDesc));
  1068. VarDesc.uFlags = (bAllUsed || fieldAnnotation.IsCBVarUsed()) ? D3D_SVF_USED : 0;
  1069. CShaderReflectionVariable Var;
  1070. //Create reflection type.
  1071. CShaderReflectionType *pVarType = new CShaderReflectionType();
  1072. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(pVarType));
  1073. pVarType->Initialize(M, ST->getContainedType(i), fieldAnnotation, fieldAnnotation.GetCBufferOffset(), allTypes, true);
  1074. // Replicate fxc bug, where Elements == 1 for inner struct of CB array, instead of 0.
  1075. if (CB.GetRangeSize() > 1) {
  1076. DXASSERT(pVarType->m_Desc.Elements == 0,
  1077. "otherwise, assumption is wrong");
  1078. pVarType->m_Desc.Elements = 1;
  1079. } else if (CB.GetHLSLType()
  1080. ->getPointerElementType()
  1081. ->isArrayTy() &&
  1082. CB.GetRangeSize() == 1) {
  1083. // Set elements to 1 for size 1 array.
  1084. pVarType->m_Desc.Elements = 1;
  1085. }
  1086. BYTE *pDefaultValue = nullptr;
  1087. VarDesc.Name = fieldAnnotation.GetFieldName().c_str();
  1088. VarDesc.StartOffset = fieldAnnotation.GetCBufferOffset();
  1089. VarDesc.Size = pVarType->GetCBufferSize();
  1090. Var.Initialize(this, &VarDesc, pVarType, pDefaultValue);
  1091. m_Variables.push_back(Var);
  1092. }
  1093. }
  1094. static unsigned CalcTypeSize(Type *Ty, unsigned &alignment) {
  1095. // Assume aligned values.
  1096. if (Ty->isArrayTy()) {
  1097. ArrayType *AT = dyn_cast<ArrayType>(Ty);
  1098. return AT->getNumElements() * CalcTypeSize(AT->getArrayElementType(), alignment);
  1099. }
  1100. else if (Ty->isStructTy()) {
  1101. StructType *ST = dyn_cast<StructType>(Ty);
  1102. unsigned i = 0, c = ST->getStructNumElements();
  1103. unsigned result = 0;
  1104. for (; i < c; ++i) {
  1105. unsigned memberalign = 0;
  1106. result += CalcTypeSize(ST->getStructElementType(i), memberalign);
  1107. alignment = std::max(alignment, memberalign);
  1108. result = (unsigned)RoundUpToAlignment(result, memberalign);
  1109. }
  1110. result = (unsigned)RoundUpToAlignment(result, alignment);
  1111. return result;
  1112. }
  1113. else if (Ty->isVectorTy()) {
  1114. VectorType *VT = dyn_cast<VectorType>(Ty);
  1115. return VT->getVectorNumElements() * CalcTypeSize(VT->getVectorElementType(), alignment);
  1116. }
  1117. else {
  1118. return alignment = Ty->getPrimitiveSizeInBits() / 8;
  1119. }
  1120. }
  1121. static unsigned CalcResTypeSize(DxilModule &M, DxilResource &R) {
  1122. UNREFERENCED_PARAMETER(M);
  1123. Type *Ty = R.GetHLSLType()->getPointerElementType();
  1124. if (R.IsStructuredBuffer()) {
  1125. Ty = dxilutil::StripArrayTypes(Ty);
  1126. }
  1127. return M.GetModule()->getDataLayout().getTypeAllocSize(Ty);
  1128. // Don't think we need this one if we can just use the data layout:
  1129. //unsigned alignment = 0;
  1130. //return CalcTypeSize(Ty, alignment);
  1131. }
  1132. void CShaderReflectionConstantBuffer::InitializeStructuredBuffer(
  1133. DxilModule &M,
  1134. DxilResource &R,
  1135. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes) {
  1136. ZeroMemory(&m_Desc, sizeof(m_Desc));
  1137. m_ReflectionName = R.GetGlobalName();
  1138. m_Desc.Type = D3D11_CT_RESOURCE_BIND_INFO;
  1139. m_Desc.uFlags = 0;
  1140. m_Desc.Variables = 1;
  1141. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1142. ZeroMemory(&VarDesc, sizeof(VarDesc));
  1143. VarDesc.Name = "$Element";
  1144. VarDesc.Size = CalcResTypeSize(M, R);
  1145. VarDesc.StartTexture = UINT_MAX;
  1146. VarDesc.StartSampler = UINT_MAX;
  1147. VarDesc.uFlags |= D3D_SVF_USED;
  1148. CShaderReflectionVariable Var;
  1149. // First type is an empty type: returned if no annotation available.
  1150. CShaderReflectionType *pVarType = allTypes[0].get();
  1151. // Create reflection type, if we have the necessary annotation info
  1152. // Extract the `struct` that wraps element type of the buffer resource
  1153. Type *Ty = R.GetHLSLType()->getPointerElementType();
  1154. SmallVector<unsigned, 4> arrayDims;
  1155. Ty = dxilutil::StripArrayTypes(Ty, &arrayDims);
  1156. for (unsigned i = 0; i < arrayDims.size(); ++i) {
  1157. m_ReflectionName += "[0]";
  1158. }
  1159. m_Desc.Name = m_ReflectionName.c_str();
  1160. StructType *ST = cast<StructType>(Ty);
  1161. // Look up struct type annotation on the element type
  1162. DxilTypeSystem &typeSys = M.GetTypeSystem();
  1163. DxilStructAnnotation *annotation =
  1164. typeSys.GetStructAnnotation(cast<StructType>(ST));
  1165. // Dxil from dxbc doesn't have annotation.
  1166. if(annotation)
  1167. {
  1168. // Actually create the reflection type.
  1169. pVarType = new CShaderReflectionType();
  1170. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(pVarType));
  1171. // The user-visible element type is the first field of the wrapepr `struct`
  1172. Type *fieldType = ST->getElementType(0);
  1173. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(0);
  1174. pVarType->Initialize(M, fieldType, fieldAnnotation, 0, allTypes, false);
  1175. }
  1176. BYTE *pDefaultValue = nullptr;
  1177. Var.Initialize(this, &VarDesc, pVarType, pDefaultValue);
  1178. m_Variables.push_back(Var);
  1179. m_Desc.Size = VarDesc.Size;
  1180. }
  1181. void CShaderReflectionConstantBuffer::InitializeTBuffer(
  1182. DxilModule &M,
  1183. DxilResource &R,
  1184. std::vector<std::unique_ptr<CShaderReflectionType>>& allTypes,
  1185. bool bUsageInMetadata) {
  1186. ZeroMemory(&m_Desc, sizeof(m_Desc));
  1187. m_ReflectionName = R.GetGlobalName();
  1188. m_Desc.Type = D3D11_CT_TBUFFER;
  1189. m_Desc.uFlags = 0;
  1190. Type *Ty = R.GetHLSLType()->getPointerElementType();
  1191. DxilTypeSystem &typeSys = M.GetTypeSystem();
  1192. StructType *ST = cast<StructType>(Ty);
  1193. DxilStructAnnotation *annotation =
  1194. typeSys.GetStructAnnotation(cast<StructType>(ST));
  1195. // Dxil from dxbc doesn't have annotation.
  1196. if (!annotation)
  1197. return;
  1198. m_Desc.Name = m_ReflectionName.c_str();
  1199. m_Desc.Variables = ST->getNumContainedTypes();
  1200. // If only one member, it's used if it's here.
  1201. bool bAllUsed = ST->getNumContainedTypes() < 2;
  1202. bAllUsed |= !bUsageInMetadata; // Will update in SetCBufferUsage.
  1203. for (unsigned i = 0; i < ST->getNumContainedTypes(); ++i) {
  1204. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(i);
  1205. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1206. ZeroMemory(&VarDesc, sizeof(VarDesc));
  1207. VarDesc.uFlags = (bAllUsed || fieldAnnotation.IsCBVarUsed()) ? D3D_SVF_USED : 0;
  1208. CShaderReflectionVariable Var;
  1209. //Create reflection type.
  1210. CShaderReflectionType *pVarType = new CShaderReflectionType();
  1211. allTypes.push_back(std::unique_ptr<CShaderReflectionType>(pVarType));
  1212. pVarType->Initialize(M, ST->getContainedType(i), fieldAnnotation, fieldAnnotation.GetCBufferOffset(), allTypes, true);
  1213. BYTE *pDefaultValue = nullptr;
  1214. VarDesc.Name = fieldAnnotation.GetFieldName().c_str();
  1215. VarDesc.StartOffset = fieldAnnotation.GetCBufferOffset();
  1216. VarDesc.Size = pVarType->GetCBufferSize();
  1217. VarDesc.StartTexture = UINT_MAX;
  1218. VarDesc.StartSampler = UINT_MAX;
  1219. Var.Initialize(this, &VarDesc, pVarType, pDefaultValue);
  1220. m_Variables.push_back(Var);
  1221. m_Desc.Size = std::max(m_Desc.Size, VarDesc.StartOffset + VarDesc.Size);
  1222. }
  1223. m_Desc.Size = (m_Desc.Size + 0x0f) & ~(0x0f); // Round up to 16 bytes for reflection.
  1224. }
  1225. HRESULT CShaderReflectionConstantBuffer::GetDesc(D3D12_SHADER_BUFFER_DESC *pDesc) {
  1226. if (!pDesc)
  1227. return E_POINTER;
  1228. memcpy(pDesc, &m_Desc, sizeof(m_Desc));
  1229. return S_OK;
  1230. }
  1231. ID3D12ShaderReflectionVariable *
  1232. CShaderReflectionConstantBuffer::GetVariableByIndex(UINT Index) {
  1233. if (Index >= m_Variables.size()) {
  1234. return &g_InvalidSRVariable;
  1235. }
  1236. return &m_Variables[Index];
  1237. }
  1238. ID3D12ShaderReflectionVariable *
  1239. CShaderReflectionConstantBuffer::GetVariableByName(LPCSTR Name) {
  1240. UINT index;
  1241. if (NULL == Name) {
  1242. return &g_InvalidSRVariable;
  1243. }
  1244. for (index = 0; index < m_Variables.size(); ++index) {
  1245. if (0 == strcmp(m_Variables[index].GetName(), Name)) {
  1246. return &m_Variables[index];
  1247. }
  1248. }
  1249. return &g_InvalidSRVariable;
  1250. }
  1251. ///////////////////////////////////////////////////////////////////////////////
  1252. // DxilShaderReflection implementation. //
  1253. static DxilResource *DxilResourceFromBase(DxilResourceBase *RB) {
  1254. DxilResourceBase::Class C = RB->GetClass();
  1255. if (C == DXIL::ResourceClass::UAV || C == DXIL::ResourceClass::SRV)
  1256. return (DxilResource *)RB;
  1257. return nullptr;
  1258. }
  1259. static D3D_SHADER_INPUT_TYPE ResourceToShaderInputType(DxilResourceBase *RB) {
  1260. DxilResource *R = DxilResourceFromBase(RB);
  1261. bool isUAV = RB->GetClass() == DxilResourceBase::Class::UAV;
  1262. switch (RB->GetKind()) {
  1263. case DxilResource::Kind::CBuffer:
  1264. return D3D_SIT_CBUFFER;
  1265. case DxilResource::Kind::Sampler:
  1266. return D3D_SIT_SAMPLER;
  1267. case DxilResource::Kind::RawBuffer:
  1268. return isUAV ? D3D_SIT_UAV_RWBYTEADDRESS : D3D_SIT_BYTEADDRESS;
  1269. case DxilResource::Kind::StructuredBuffer: {
  1270. if (!isUAV) return D3D_SIT_STRUCTURED;
  1271. // TODO: D3D_SIT_UAV_CONSUME_STRUCTURED, D3D_SIT_UAV_APPEND_STRUCTURED?
  1272. if (R->HasCounter()) return D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER;
  1273. return D3D_SIT_UAV_RWSTRUCTURED;
  1274. }
  1275. case DxilResource::Kind::TBuffer:
  1276. return D3D_SIT_TBUFFER;
  1277. case DxilResource::Kind::TypedBuffer:
  1278. case DxilResource::Kind::Texture1D:
  1279. case DxilResource::Kind::Texture1DArray:
  1280. case DxilResource::Kind::Texture2D:
  1281. case DxilResource::Kind::Texture2DArray:
  1282. case DxilResource::Kind::Texture2DMS:
  1283. case DxilResource::Kind::Texture2DMSArray:
  1284. case DxilResource::Kind::Texture3D:
  1285. case DxilResource::Kind::TextureCube:
  1286. case DxilResource::Kind::TextureCubeArray:
  1287. return isUAV ? D3D_SIT_UAV_RWTYPED : D3D_SIT_TEXTURE;
  1288. case DxilResource::Kind::RTAccelerationStructure:
  1289. return (D3D_SHADER_INPUT_TYPE)(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 1); // D3D_SIT_RTACCELERATIONSTRUCTURE
  1290. case DxilResource::Kind::FeedbackTexture2D:
  1291. case DxilResource::Kind::FeedbackTexture2DArray:
  1292. return (D3D_SHADER_INPUT_TYPE)(D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER + 2); // D3D_SIT_UAV_FEEDBACKTEXTURE
  1293. default:
  1294. return (D3D_SHADER_INPUT_TYPE)-1;
  1295. }
  1296. }
  1297. static D3D_RESOURCE_RETURN_TYPE ResourceToReturnType(DxilResourceBase *RB) {
  1298. DxilResource *R = DxilResourceFromBase(RB);
  1299. if (R != nullptr && !R->IsTBuffer()) {
  1300. CompType CT = R->GetCompType();
  1301. if (CT.GetKind() == CompType::Kind::F64) return D3D_RETURN_TYPE_DOUBLE;
  1302. if (CT.IsUNorm()) return D3D_RETURN_TYPE_UNORM;
  1303. if (CT.IsSNorm()) return D3D_RETURN_TYPE_SNORM;
  1304. if (CT.IsSIntTy()) return D3D_RETURN_TYPE_SINT;
  1305. if (CT.IsUIntTy()) return D3D_RETURN_TYPE_UINT;
  1306. if (CT.IsFloatTy()) return D3D_RETURN_TYPE_FLOAT;
  1307. // D3D_RETURN_TYPE_CONTINUED: Return type is a multiple-dword type, such as a
  1308. // double or uint64, and the component is continued from the previous
  1309. // component that was declared. The first component represents the lower bits.
  1310. return D3D_RETURN_TYPE_MIXED;
  1311. }
  1312. return (D3D_RESOURCE_RETURN_TYPE)0;
  1313. }
  1314. static D3D_SRV_DIMENSION ResourceToDimension(DxilResourceBase *RB) {
  1315. switch (RB->GetKind()) {
  1316. case DxilResource::Kind::StructuredBuffer:
  1317. case DxilResource::Kind::TypedBuffer:
  1318. return D3D_SRV_DIMENSION_BUFFER;
  1319. case DxilResource::Kind::TBuffer:
  1320. return D3D_SRV_DIMENSION_UNKNOWN; // Fxc returns this
  1321. case DxilResource::Kind::Texture1D:
  1322. return D3D_SRV_DIMENSION_TEXTURE1D;
  1323. case DxilResource::Kind::Texture1DArray:
  1324. return D3D_SRV_DIMENSION_TEXTURE1DARRAY;
  1325. case DxilResource::Kind::Texture2D:
  1326. case DxilResource::Kind::FeedbackTexture2D:
  1327. return D3D_SRV_DIMENSION_TEXTURE2D;
  1328. case DxilResource::Kind::Texture2DArray:
  1329. case DxilResource::Kind::FeedbackTexture2DArray:
  1330. return D3D_SRV_DIMENSION_TEXTURE2DARRAY;
  1331. case DxilResource::Kind::Texture2DMS:
  1332. return D3D_SRV_DIMENSION_TEXTURE2DMS;
  1333. case DxilResource::Kind::Texture2DMSArray:
  1334. return D3D_SRV_DIMENSION_TEXTURE2DMSARRAY;
  1335. case DxilResource::Kind::Texture3D:
  1336. return D3D_SRV_DIMENSION_TEXTURE3D;
  1337. case DxilResource::Kind::TextureCube:
  1338. return D3D_SRV_DIMENSION_TEXTURECUBE;
  1339. case DxilResource::Kind::TextureCubeArray:
  1340. return D3D_SRV_DIMENSION_TEXTURECUBEARRAY;
  1341. case DxilResource::Kind::RawBuffer:
  1342. return D3D11_SRV_DIMENSION_BUFFER; // D3D11_SRV_DIMENSION_BUFFEREX?
  1343. default:
  1344. return D3D_SRV_DIMENSION_UNKNOWN;
  1345. }
  1346. }
  1347. static UINT ResourceToFlags(DxilResourceBase *RB) {
  1348. if (RB->GetClass() == DXIL::ResourceClass::CBuffer)
  1349. return D3D_SIF_USERPACKED;
  1350. UINT result = 0;
  1351. DxilResource *R = DxilResourceFromBase(RB);
  1352. if (R != nullptr &&
  1353. (R->IsAnyTexture() || R->GetKind() == DXIL::ResourceKind::TypedBuffer)) {
  1354. llvm::Type *RetTy = R->GetRetType();
  1355. if (VectorType *VT = dyn_cast<VectorType>(RetTy)) {
  1356. unsigned vecSize = VT->getNumElements();
  1357. switch (vecSize) {
  1358. case 4:
  1359. result |= D3D_SIF_TEXTURE_COMPONENTS;
  1360. break;
  1361. case 3:
  1362. result |= D3D_SIF_TEXTURE_COMPONENT_1;
  1363. break;
  1364. case 2:
  1365. result |= D3D_SIF_TEXTURE_COMPONENT_0;
  1366. break;
  1367. }
  1368. }
  1369. } else if (R && R->IsTBuffer()) {
  1370. return D3D_SIF_USERPACKED;
  1371. } else if (RB->GetClass() == DXIL::ResourceClass::Sampler) {
  1372. DxilSampler *S = static_cast<DxilSampler *>(RB);
  1373. if (S->GetSamplerKind() == DXIL::SamplerKind::Comparison)
  1374. result |= D3D_SIF_COMPARISON_SAMPLER;
  1375. }
  1376. return result;
  1377. }
  1378. void DxilModuleReflection::CreateReflectionObjectForResource(DxilResourceBase *RB) {
  1379. DxilResourceBase::Class C = RB->GetClass();
  1380. DxilResource *R =
  1381. (C == DXIL::ResourceClass::UAV || C == DXIL::ResourceClass::SRV)
  1382. ? (DxilResource *)RB
  1383. : nullptr;
  1384. D3D12_SHADER_INPUT_BIND_DESC inputBind;
  1385. ZeroMemory(&inputBind, sizeof(inputBind));
  1386. inputBind.BindCount = RB->GetRangeSize();
  1387. // FXC Bug: For Unbounded range, CBuffers say bind count is UINT_MAX, but all others report 0!
  1388. if (RB->GetRangeSize() == UINT_MAX && C != DXIL::ResourceClass::CBuffer)
  1389. inputBind.BindCount = 0;
  1390. inputBind.BindPoint = RB->GetLowerBound();
  1391. inputBind.Dimension = ResourceToDimension(RB);
  1392. inputBind.Name = RB->GetGlobalName().c_str();
  1393. inputBind.Type = ResourceToShaderInputType(RB);
  1394. if (R == nullptr) {
  1395. inputBind.NumSamples = 0;
  1396. }
  1397. else {
  1398. inputBind.NumSamples = R->GetSampleCount();
  1399. if (inputBind.NumSamples == 0) {
  1400. if (R->IsStructuredBuffer()) {
  1401. inputBind.NumSamples = CalcResTypeSize(*m_pDxilModule, *R);
  1402. } else if (!R->IsRawBuffer() && !R->IsTBuffer() &&
  1403. R->GetKind() != DXIL::ResourceKind::Texture2DMS &&
  1404. R->GetKind() != DXIL::ResourceKind::Texture2DMSArray) {
  1405. inputBind.NumSamples = 0xFFFFFFFF;
  1406. }
  1407. }
  1408. }
  1409. inputBind.ReturnType = ResourceToReturnType(RB);
  1410. inputBind.Space = RB->GetSpaceID();
  1411. inputBind.uFlags = ResourceToFlags(RB);
  1412. inputBind.uID = RB->GetID();
  1413. m_Resources.push_back(inputBind);
  1414. }
  1415. // Find the imm offset part from a value.
  1416. // It must exist unless offset is 0.
  1417. static unsigned GetCBOffset(Value *V) {
  1418. if (ConstantInt *Imm = dyn_cast<ConstantInt>(V))
  1419. return Imm->getLimitedValue();
  1420. else if (UnaryInstruction *UI = dyn_cast<UnaryInstruction>(V)) {
  1421. return 0;
  1422. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(V)) {
  1423. switch (BO->getOpcode()) {
  1424. case Instruction::Add: {
  1425. unsigned left = GetCBOffset(BO->getOperand(0));
  1426. unsigned right = GetCBOffset(BO->getOperand(1));
  1427. return left + right;
  1428. } break;
  1429. case Instruction::Or: {
  1430. unsigned left = GetCBOffset(BO->getOperand(0));
  1431. unsigned right = GetCBOffset(BO->getOperand(1));
  1432. return left | right;
  1433. } break;
  1434. default:
  1435. return 0;
  1436. }
  1437. } else {
  1438. return 0;
  1439. }
  1440. }
  1441. static unsigned GetOffsetForCBExtractValue(ExtractValueInst *EV, bool bMinPrecision) {
  1442. DXASSERT(EV->getNumIndices() == 1, "otherwise, unexpected indices/type for extractvalue");
  1443. unsigned typeSize = 4;
  1444. unsigned bits = EV->getType()->getScalarSizeInBits();
  1445. if (bits == 64)
  1446. typeSize = 8;
  1447. else if (bits == 16 && !bMinPrecision)
  1448. typeSize = 2;
  1449. return (EV->getIndices().front() * typeSize);
  1450. }
  1451. static void CollectInPhiChain(PHINode *cbUser, std::vector<unsigned> &cbufUsage,
  1452. unsigned offset, std::unordered_set<Value *> &userSet,
  1453. bool bMinPrecision) {
  1454. if (userSet.count(cbUser) > 0)
  1455. return;
  1456. userSet.insert(cbUser);
  1457. for (User *cbU : cbUser->users()) {
  1458. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(cbU)) {
  1459. cbufUsage.emplace_back(offset + GetOffsetForCBExtractValue(EV, bMinPrecision));
  1460. } else {
  1461. PHINode *phi = cast<PHINode>(cbU);
  1462. CollectInPhiChain(phi, cbufUsage, offset, userSet, bMinPrecision);
  1463. }
  1464. }
  1465. }
  1466. static void CollectCBufUsage(Value *cbHandle,
  1467. std::vector<unsigned> &cbufUsage,
  1468. bool bMinPrecision) {
  1469. for (User *U : cbHandle->users()) {
  1470. CallInst *CI = cast<CallInst>(U);
  1471. ConstantInt *opcodeV =
  1472. cast<ConstantInt>(CI->getArgOperand(DXIL::OperandIndex::kOpcodeIdx));
  1473. DXIL::OpCode opcode = static_cast<DXIL::OpCode>(opcodeV->getLimitedValue());
  1474. if (opcode == DXIL::OpCode::CBufferLoadLegacy) {
  1475. DxilInst_CBufferLoadLegacy cbload(CI);
  1476. Value *resIndex = cbload.get_regIndex();
  1477. unsigned offset = GetCBOffset(resIndex);
  1478. // 16 bytes align.
  1479. offset <<= 4;
  1480. for (User *cbU : U->users()) {
  1481. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(cbU)) {
  1482. cbufUsage.emplace_back(offset + GetOffsetForCBExtractValue(EV, bMinPrecision));
  1483. } else {
  1484. PHINode *phi = cast<PHINode>(cbU);
  1485. std::unordered_set<Value *> userSet;
  1486. CollectInPhiChain(phi, cbufUsage, offset, userSet, bMinPrecision);
  1487. }
  1488. }
  1489. } else if (opcode == DXIL::OpCode::CBufferLoad) {
  1490. DxilInst_CBufferLoad cbload(CI);
  1491. Value *byteOffset = cbload.get_byteOffset();
  1492. unsigned offset = GetCBOffset(byteOffset);
  1493. cbufUsage.emplace_back(offset);
  1494. } else if (opcode == DXIL::OpCode::AnnotateHandle) {
  1495. DxilInst_AnnotateHandle annotateHandle(CI);
  1496. Value *annotatedHandle = annotateHandle.get_res();
  1497. CollectCBufUsage(annotatedHandle, cbufUsage, bMinPrecision);
  1498. } else {
  1499. //
  1500. DXASSERT(0, "invalid opcode");
  1501. }
  1502. }
  1503. }
  1504. static void SetCBufVarUsage(CShaderReflectionConstantBuffer &cb,
  1505. std::vector<unsigned> &usage) {
  1506. D3D12_SHADER_BUFFER_DESC Desc;
  1507. if (FAILED(cb.GetDesc(&Desc)))
  1508. return;
  1509. unsigned size = Desc.Variables;
  1510. std::sort(usage.begin(), usage.end());
  1511. for (unsigned i = 0; i < size; i++) {
  1512. ID3D12ShaderReflectionVariable *pVar = cb.GetVariableByIndex(i);
  1513. D3D12_SHADER_VARIABLE_DESC VarDesc;
  1514. if (FAILED(pVar->GetDesc(&VarDesc)))
  1515. continue;
  1516. if (!pVar)
  1517. continue;
  1518. unsigned begin = VarDesc.StartOffset;
  1519. unsigned end = begin + VarDesc.Size;
  1520. auto beginIt = std::find_if(usage.begin(), usage.end(),
  1521. [&](unsigned v) { return v >= begin; });
  1522. auto endIt = std::find_if(usage.begin(), usage.end(),
  1523. [&](unsigned v) { return v >= end; });
  1524. bool used = beginIt != endIt;
  1525. // Clear used.
  1526. if (!used) {
  1527. CShaderReflectionType *pVarType = (CShaderReflectionType *)pVar->GetType();
  1528. BYTE *pDefaultValue = nullptr;
  1529. VarDesc.uFlags &= ~D3D_SVF_USED;
  1530. CShaderReflectionVariable *pCVarDesc = (CShaderReflectionVariable*)pVar;
  1531. pCVarDesc->Initialize(&cb, &VarDesc, pVarType, pDefaultValue);
  1532. }
  1533. }
  1534. }
  1535. void DxilShaderReflection::SetCBufferUsage() {
  1536. hlsl::OP *hlslOP = m_pDxilModule->GetOP();
  1537. LLVMContext &Ctx = m_pDxilModule->GetCtx();
  1538. // Indexes >= cbuffer size from DxilModule are SRV or UAV structured buffers.
  1539. // We only collect usage for actual cbuffers, so don't go clearing usage on other buffers.
  1540. unsigned cbSize = std::min(m_CBs.size(), m_pDxilModule->GetCBuffers().size());
  1541. std::vector< std::vector<unsigned> > cbufUsage(cbSize);
  1542. Function *createHandle = hlslOP->GetOpFunc(DXIL::OpCode::CreateHandle, Type::getVoidTy(Ctx));
  1543. if (createHandle->user_empty()) {
  1544. createHandle->eraseFromParent();
  1545. return;
  1546. }
  1547. // Find all cb handles.
  1548. for (User *U : createHandle->users()) {
  1549. DxilInst_CreateHandle handle(cast<CallInst>(U));
  1550. Value *resClass = handle.get_resourceClass();
  1551. ConstantInt *immResClass = cast<ConstantInt>(resClass);
  1552. if (immResClass->getLimitedValue() == (unsigned)DXIL::ResourceClass::CBuffer) {
  1553. ConstantInt *cbID = cast<ConstantInt>(handle.get_rangeId());
  1554. CollectCBufUsage(U, cbufUsage[cbID->getLimitedValue()], m_pDxilModule->GetUseMinPrecision());
  1555. }
  1556. }
  1557. for (unsigned i=0;i<cbSize;i++) {
  1558. SetCBufVarUsage(*m_CBs[i], cbufUsage[i]);
  1559. }
  1560. }
  1561. void DxilModuleReflection::CreateReflectionObjects() {
  1562. DXASSERT_NOMSG(m_pDxilModule != nullptr);
  1563. {
  1564. // Add empty type for when no type info is available, instead of returning nullptr.
  1565. DXASSERT_NOMSG(m_Types.empty());
  1566. CShaderReflectionType *pEmptyType = new CShaderReflectionType();
  1567. m_Types.push_back(std::unique_ptr<CShaderReflectionType>(pEmptyType));
  1568. pEmptyType->InitializeEmpty();
  1569. }
  1570. // Create constant buffers, resources and signatures.
  1571. for (auto && cb : m_pDxilModule->GetCBuffers()) {
  1572. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1573. rcb->Initialize(*m_pDxilModule, *(cb.get()), m_Types, m_bUsageInMetadata);
  1574. m_CBsByName[rcb->GetName()] = (UINT)m_CBs.size();
  1575. m_CBs.emplace_back(std::move(rcb));
  1576. }
  1577. // TODO: add tbuffers into m_CBs
  1578. for (auto && uav : m_pDxilModule->GetUAVs()) {
  1579. if (!DXIL::IsStructuredBuffer(uav->GetKind())) {
  1580. continue;
  1581. }
  1582. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1583. rcb->InitializeStructuredBuffer(*m_pDxilModule, *(uav.get()), m_Types);
  1584. m_StructuredBufferCBsByName[rcb->GetName()] = (UINT)m_CBs.size();
  1585. m_CBs.emplace_back(std::move(rcb));
  1586. }
  1587. for (auto && srv : m_pDxilModule->GetSRVs()) {
  1588. if (srv->GetKind() != DxilResource::Kind::StructuredBuffer &&
  1589. srv->GetKind() != DxilResource::Kind::TBuffer) {
  1590. continue;
  1591. }
  1592. std::unique_ptr<CShaderReflectionConstantBuffer> rcb(new CShaderReflectionConstantBuffer());
  1593. if (srv->GetKind() == DxilResource::Kind::TBuffer) {
  1594. rcb->InitializeTBuffer(*m_pDxilModule, *(srv.get()), m_Types, m_bUsageInMetadata);
  1595. m_CBsByName[rcb->GetName()] = (UINT)m_CBs.size();
  1596. } else {
  1597. rcb->InitializeStructuredBuffer(*m_pDxilModule, *(srv.get()), m_Types);
  1598. m_StructuredBufferCBsByName[rcb->GetName()] = (UINT)m_CBs.size();
  1599. }
  1600. m_CBs.emplace_back(std::move(rcb));
  1601. }
  1602. // Populate all resources.
  1603. for (auto && cbRes : m_pDxilModule->GetCBuffers()) {
  1604. CreateReflectionObjectForResource(cbRes.get());
  1605. }
  1606. for (auto && samplerRes : m_pDxilModule->GetSamplers()) {
  1607. CreateReflectionObjectForResource(samplerRes.get());
  1608. }
  1609. for (auto && srvRes : m_pDxilModule->GetSRVs()) {
  1610. CreateReflectionObjectForResource(srvRes.get());
  1611. }
  1612. for (auto && uavRes : m_pDxilModule->GetUAVs()) {
  1613. CreateReflectionObjectForResource(uavRes.get());
  1614. }
  1615. }
  1616. static D3D_REGISTER_COMPONENT_TYPE CompTypeToRegisterComponentType(CompType CT) {
  1617. switch (CT.GetKind()) {
  1618. case DXIL::ComponentType::F16:
  1619. case DXIL::ComponentType::F32:
  1620. return D3D_REGISTER_COMPONENT_FLOAT32;
  1621. case DXIL::ComponentType::I1:
  1622. case DXIL::ComponentType::U16:
  1623. case DXIL::ComponentType::U32:
  1624. return D3D_REGISTER_COMPONENT_UINT32;
  1625. case DXIL::ComponentType::I16:
  1626. case DXIL::ComponentType::I32:
  1627. return D3D_REGISTER_COMPONENT_SINT32;
  1628. default:
  1629. return D3D_REGISTER_COMPONENT_UNKNOWN;
  1630. }
  1631. }
  1632. static D3D_MIN_PRECISION CompTypeToMinPrecision(CompType CT) {
  1633. switch (CT.GetKind()) {
  1634. case DXIL::ComponentType::F16:
  1635. return D3D_MIN_PRECISION_FLOAT_16;
  1636. case DXIL::ComponentType::I16:
  1637. return D3D_MIN_PRECISION_SINT_16;
  1638. case DXIL::ComponentType::U16:
  1639. return D3D_MIN_PRECISION_UINT_16;
  1640. default:
  1641. return D3D_MIN_PRECISION_DEFAULT;
  1642. }
  1643. }
  1644. D3D_NAME SemanticToSystemValueType(const Semantic *S, DXIL::TessellatorDomain domain) {
  1645. switch (S->GetKind()) {
  1646. case Semantic::Kind::ClipDistance:
  1647. return D3D_NAME_CLIP_DISTANCE;
  1648. case Semantic::Kind::Arbitrary:
  1649. return D3D_NAME_UNDEFINED;
  1650. case Semantic::Kind::VertexID:
  1651. return D3D_NAME_VERTEX_ID;
  1652. case Semantic::Kind::InstanceID:
  1653. return D3D_NAME_INSTANCE_ID;
  1654. case Semantic::Kind::Position:
  1655. return D3D_NAME_POSITION;
  1656. case Semantic::Kind::Coverage:
  1657. return D3D_NAME_COVERAGE;
  1658. case Semantic::Kind::InnerCoverage:
  1659. return D3D_NAME_INNER_COVERAGE;
  1660. case Semantic::Kind::PrimitiveID:
  1661. return D3D_NAME_PRIMITIVE_ID;
  1662. case Semantic::Kind::SampleIndex:
  1663. return D3D_NAME_SAMPLE_INDEX;
  1664. case Semantic::Kind::IsFrontFace:
  1665. return D3D_NAME_IS_FRONT_FACE;
  1666. case Semantic::Kind::RenderTargetArrayIndex:
  1667. return D3D_NAME_RENDER_TARGET_ARRAY_INDEX;
  1668. case Semantic::Kind::ViewPortArrayIndex:
  1669. return D3D_NAME_VIEWPORT_ARRAY_INDEX;
  1670. case Semantic::Kind::CullDistance:
  1671. return D3D_NAME_CULL_DISTANCE;
  1672. case Semantic::Kind::Target:
  1673. return D3D_NAME_TARGET;
  1674. case Semantic::Kind::Depth:
  1675. return D3D_NAME_DEPTH;
  1676. case Semantic::Kind::DepthLessEqual:
  1677. return D3D_NAME_DEPTH_LESS_EQUAL;
  1678. case Semantic::Kind::DepthGreaterEqual:
  1679. return D3D_NAME_DEPTH_GREATER_EQUAL;
  1680. case Semantic::Kind::StencilRef:
  1681. return D3D_NAME_STENCIL_REF;
  1682. case Semantic::Kind::TessFactor: {
  1683. switch (domain) {
  1684. case DXIL::TessellatorDomain::IsoLine:
  1685. return D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR;
  1686. case DXIL::TessellatorDomain::Tri:
  1687. return D3D_NAME_FINAL_TRI_EDGE_TESSFACTOR;
  1688. case DXIL::TessellatorDomain::Quad:
  1689. return D3D_NAME_FINAL_QUAD_EDGE_TESSFACTOR;
  1690. default:
  1691. return D3D_NAME_UNDEFINED;
  1692. }
  1693. case Semantic::Kind::ShadingRate:
  1694. return (D3D_NAME)DxilProgramSigSemantic::ShadingRate;
  1695. case Semantic::Kind::CullPrimitive:
  1696. return (D3D_NAME)DxilProgramSigSemantic::CullPrimitive;
  1697. }
  1698. case Semantic::Kind::InsideTessFactor:
  1699. switch (domain) {
  1700. case DXIL::TessellatorDomain::Tri:
  1701. return D3D_NAME_FINAL_TRI_INSIDE_TESSFACTOR;
  1702. case DXIL::TessellatorDomain::Quad:
  1703. return D3D_NAME_FINAL_QUAD_INSIDE_TESSFACTOR;
  1704. default:
  1705. return D3D_NAME_UNDEFINED;
  1706. }
  1707. case Semantic::Kind::DispatchThreadID:
  1708. case Semantic::Kind::GroupID:
  1709. case Semantic::Kind::GroupIndex:
  1710. case Semantic::Kind::GroupThreadID:
  1711. case Semantic::Kind::DomainLocation:
  1712. case Semantic::Kind::OutputControlPointID:
  1713. case Semantic::Kind::GSInstanceID:
  1714. case Semantic::Kind::Invalid:
  1715. default:
  1716. return D3D_NAME_UNDEFINED;
  1717. }
  1718. }
  1719. static uint8_t NegMask(uint8_t V) {
  1720. V ^= 0xF;
  1721. return V & 0xF;
  1722. }
  1723. void DxilShaderReflection::CreateReflectionObjectsForSignature(
  1724. const DxilSignature &Sig,
  1725. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> &Descs) {
  1726. for (auto && SigElem : Sig.GetElements()) {
  1727. D3D12_SIGNATURE_PARAMETER_DESC Desc;
  1728. Desc.ComponentType = CompTypeToRegisterComponentType(SigElem->GetCompType());
  1729. Desc.Mask = SigElem->GetColsAsMask();
  1730. // D3D11_43 does not have MinPrecison.
  1731. if (m_PublicAPI != PublicAPI::D3D11_43)
  1732. Desc.MinPrecision = CompTypeToMinPrecision(SigElem->GetCompType());
  1733. if (m_bUsageInMetadata) {
  1734. unsigned UsageMask = SigElem->GetUsageMask();
  1735. if (SigElem->IsAllocated())
  1736. UsageMask <<= SigElem->GetStartCol();
  1737. Desc.ReadWriteMask = Sig.IsInput() ? UsageMask : NegMask(UsageMask);
  1738. } else {
  1739. Desc.ReadWriteMask = Sig.IsInput() ? 0 : Desc.Mask; // Start with output-never-written/input-never-read.
  1740. }
  1741. Desc.Register = SigElem->GetStartRow();
  1742. Desc.Stream = SigElem->GetOutputStream();
  1743. Desc.SystemValueType = SemanticToSystemValueType(SigElem->GetSemantic(), m_pDxilModule->GetTessellatorDomain());
  1744. Desc.SemanticName = SigElem->GetName();
  1745. if (!SigElem->GetSemantic()->IsArbitrary())
  1746. Desc.SemanticName = CreateUpperCase(Desc.SemanticName);
  1747. const std::vector<unsigned> &indexVec = SigElem->GetSemanticIndexVec();
  1748. for (unsigned semIdx = 0; semIdx < indexVec.size(); ++semIdx) {
  1749. Desc.SemanticIndex = indexVec[semIdx];
  1750. if (Desc.SystemValueType == D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR &&
  1751. Desc.SemanticIndex == 1)
  1752. Desc.SystemValueType = D3D_NAME_FINAL_LINE_DETAIL_TESSFACTOR;
  1753. Descs.push_back(Desc);
  1754. }
  1755. }
  1756. }
  1757. LPCSTR DxilShaderReflection::CreateUpperCase(LPCSTR pValue) {
  1758. // Restricted only to [a-z] ASCII.
  1759. LPCSTR pCursor = pValue;
  1760. while (*pCursor != '\0') {
  1761. if ('a' <= *pCursor && *pCursor <= 'z') {
  1762. break;
  1763. }
  1764. ++pCursor;
  1765. }
  1766. if (*pCursor == '\0')
  1767. return pValue;
  1768. std::unique_ptr<char[]> pUpperStr = llvm::make_unique<char[]>(strlen(pValue) + 1);
  1769. char *pWrite = pUpperStr.get();
  1770. pCursor = pValue;
  1771. for (;;) {
  1772. *pWrite = *pCursor;
  1773. if ('a' <= *pWrite && *pWrite <= 'z') {
  1774. *pWrite += ('A' - 'a');
  1775. }
  1776. if (*pWrite == '\0') break;
  1777. ++pWrite;
  1778. ++pCursor;
  1779. }
  1780. m_UpperCaseNames.push_back(std::move(pUpperStr));
  1781. return m_UpperCaseNames.back().get();
  1782. }
  1783. HRESULT DxilModuleReflection::LoadRDAT(const DxilPartHeader *pPart) {
  1784. if (pPart) {
  1785. IFRBOOL(m_RDAT.InitFromRDAT(GetDxilPartData(pPart), pPart->PartSize), DXC_E_CONTAINER_INVALID);
  1786. }
  1787. return S_OK;
  1788. }
  1789. HRESULT DxilModuleReflection::LoadModule(const DxilPartHeader *pShaderPart) {
  1790. if (pShaderPart == nullptr)
  1791. return E_INVALIDARG;
  1792. const char *pData = GetDxilPartData(pShaderPart);
  1793. try {
  1794. const char *pBitcode;
  1795. uint32_t bitcodeLength;
  1796. GetDxilProgramBitcode((DxilProgramHeader *)pData, &pBitcode, &bitcodeLength);
  1797. std::unique_ptr<MemoryBuffer> pMemBuffer =
  1798. MemoryBuffer::getMemBufferCopy(StringRef(pBitcode, bitcodeLength));
  1799. bool bBitcodeLoadError = false;
  1800. auto errorHandler = [&bBitcodeLoadError](const DiagnosticInfo &diagInfo) {
  1801. bBitcodeLoadError |= diagInfo.getSeverity() == DS_Error;
  1802. };
  1803. #if 0 // We materialize eagerly, because we'll need to walk instructions to look for usage information.
  1804. ErrorOr<std::unique_ptr<Module>> mod =
  1805. getLazyBitcodeModule(std::move(pMemBuffer), Context, errorHandler);
  1806. #else
  1807. ErrorOr<std::unique_ptr<Module>> mod =
  1808. parseBitcodeFile(pMemBuffer->getMemBufferRef(), Context, errorHandler);
  1809. #endif
  1810. if (!mod || bBitcodeLoadError) {
  1811. return E_INVALIDARG;
  1812. }
  1813. std::swap(m_pModule, mod.get());
  1814. m_pDxilModule = &m_pModule->GetOrCreateDxilModule();
  1815. unsigned ValMajor, ValMinor;
  1816. m_pDxilModule->GetValidatorVersion(ValMajor, ValMinor);
  1817. m_bUsageInMetadata = hlsl::DXIL::CompareVersions(ValMajor, ValMinor, 1, 5) >= 0;
  1818. CreateReflectionObjects();
  1819. return S_OK;
  1820. }
  1821. CATCH_CPP_RETURN_HRESULT();
  1822. };
  1823. HRESULT DxilShaderReflection::Load(const DxilPartHeader *pModulePart,
  1824. const DxilPartHeader *pRDATPart) {
  1825. IFR(LoadRDAT(pRDATPart));
  1826. IFR(LoadModule(pModulePart));
  1827. try {
  1828. // Set cbuf usage.
  1829. if (!m_bUsageInMetadata)
  1830. SetCBufferUsage();
  1831. // Populate input/output/patch constant signatures.
  1832. CreateReflectionObjectsForSignature(m_pDxilModule->GetInputSignature(), m_InputSignature);
  1833. CreateReflectionObjectsForSignature(m_pDxilModule->GetOutputSignature(), m_OutputSignature);
  1834. CreateReflectionObjectsForSignature(m_pDxilModule->GetPatchConstOrPrimSignature(), m_PatchConstantSignature);
  1835. if (!m_bUsageInMetadata)
  1836. MarkUsedSignatureElements();
  1837. InitDesc();
  1838. return S_OK;
  1839. }
  1840. CATCH_CPP_RETURN_HRESULT();
  1841. }
  1842. _Use_decl_annotations_
  1843. HRESULT DxilShaderReflection::GetDesc(D3D12_SHADER_DESC *pDesc) {
  1844. if (nullptr == pDesc) return E_POINTER;
  1845. memcpy(pDesc, &m_Desc, sizeof(D3D12_SHADER_DESC));
  1846. return S_OK;
  1847. }
  1848. static bool GetUnsignedVal(Value *V, uint32_t *pValue) {
  1849. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  1850. if (!CI) return false;
  1851. uint64_t u = CI->getZExtValue();
  1852. if (u > UINT32_MAX) return false;
  1853. *pValue = (uint32_t)u;
  1854. return true;
  1855. }
  1856. void DxilShaderReflection::MarkUsedSignatureElements() {
  1857. Function *F = m_pDxilModule->GetEntryFunction();
  1858. DXASSERT(F != nullptr, "else module load should have failed");
  1859. // For every loadInput/storeOutput, update the corresponding ReadWriteMask.
  1860. // F is a pointer to a Function instance
  1861. unsigned elementCount = m_InputSignature.size() + m_OutputSignature.size() +
  1862. m_PatchConstantSignature.size();
  1863. unsigned markedElementCount = 0;
  1864. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  1865. DxilInst_LoadInput LI(&*I);
  1866. DxilInst_StoreOutput SO(&*I);
  1867. DxilInst_LoadPatchConstant LPC(&*I);
  1868. DxilInst_StorePatchConstant SPC(&*I);
  1869. DxilInst_StoreVertexOutput SVO(&*I);
  1870. DxilInst_StorePrimitiveOutput SPO(&*I);
  1871. std::vector<D3D12_SIGNATURE_PARAMETER_DESC> *pDescs;
  1872. const DxilSignature *pSig;
  1873. uint32_t col, row, sigId;
  1874. if (LI) {
  1875. if (!GetUnsignedVal(LI.get_inputSigId(), &sigId)) continue;
  1876. if (!GetUnsignedVal(LI.get_colIndex(), &col)) continue;
  1877. GetUnsignedVal(LI.get_rowIndex(), &row);
  1878. pDescs = &m_InputSignature;
  1879. pSig = &m_pDxilModule->GetInputSignature();
  1880. }
  1881. else if (SO) {
  1882. if (!GetUnsignedVal(SO.get_outputSigId(), &sigId)) continue;
  1883. if (!GetUnsignedVal(SO.get_colIndex(), &col)) continue;
  1884. GetUnsignedVal(SO.get_rowIndex(), &row);
  1885. pDescs = &m_OutputSignature;
  1886. pSig = &m_pDxilModule->GetOutputSignature();
  1887. }
  1888. else if (SPC) {
  1889. if (!GetUnsignedVal(SPC.get_outputSigID(), &sigId)) continue;
  1890. if (!GetUnsignedVal(SPC.get_col(), &col)) continue;
  1891. GetUnsignedVal(SPC.get_row(), &row);
  1892. pDescs = &m_PatchConstantSignature;
  1893. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1894. }
  1895. else if (LPC) {
  1896. if (!GetUnsignedVal(LPC.get_inputSigId(), &sigId)) continue;
  1897. if (!GetUnsignedVal(LPC.get_col(), &col)) continue;
  1898. GetUnsignedVal(LPC.get_row(), &row);
  1899. pDescs = &m_PatchConstantSignature;
  1900. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1901. }
  1902. else if (SVO) {
  1903. if (!GetUnsignedVal(SVO.get_outputSigId(), &sigId)) continue;
  1904. if (!GetUnsignedVal(SVO.get_colIndex(), &col)) continue;
  1905. GetUnsignedVal(SVO.get_rowIndex(), &row);
  1906. pSig = &m_pDxilModule->GetOutputSignature();
  1907. }
  1908. else if (SPO) {
  1909. if (!GetUnsignedVal(SPO.get_outputSigId(), &sigId)) continue;
  1910. if (!GetUnsignedVal(SPO.get_colIndex(), &col)) continue;
  1911. GetUnsignedVal(SPO.get_rowIndex(), &row);
  1912. pSig = &m_pDxilModule->GetPatchConstOrPrimSignature();
  1913. }
  1914. else {
  1915. continue;
  1916. }
  1917. if (sigId >= pDescs->size()) continue;
  1918. D3D12_SIGNATURE_PARAMETER_DESC *pDesc = &(*pDescs)[sigId];
  1919. // Consider being more fine-grained about masks.
  1920. // We report sometimes-read on input as always-read.
  1921. unsigned UsedMask = pSig->IsInput() ? pDesc->Mask : NegMask(pDesc->Mask);
  1922. if (pDesc->ReadWriteMask == UsedMask)
  1923. continue;
  1924. pDesc->ReadWriteMask = UsedMask;
  1925. ++markedElementCount;
  1926. if (markedElementCount == elementCount)
  1927. return;
  1928. }
  1929. }
  1930. void DxilShaderReflection::InitDesc() {
  1931. D3D12_SHADER_DESC *pDesc = &m_Desc;
  1932. const DxilModule &M = *m_pDxilModule;
  1933. const ShaderModel *pSM = M.GetShaderModel();
  1934. pDesc->Version = EncodeVersion(pSM->GetKind(), pSM->GetMajor(), pSM->GetMinor());
  1935. Module *pModule = M.GetModule();
  1936. if (NamedMDNode *pIdentMD = pModule->getNamedMetadata("llvm.ident")) {
  1937. if (pIdentMD->getNumOperands()) {
  1938. if (MDNode *pMDList = pIdentMD->getOperand(0)) {
  1939. if (pMDList->getNumOperands()) {
  1940. if (MDString *pMDString = dyn_cast_or_null<MDString>(pMDList->getOperand(0))) {
  1941. pDesc->Creator = pMDString->getString().data();
  1942. }
  1943. }
  1944. }
  1945. }
  1946. }
  1947. // Unset: UINT Flags; // Shader compilation/parse flags
  1948. pDesc->ConstantBuffers = m_CBs.size();
  1949. pDesc->BoundResources = m_Resources.size();
  1950. pDesc->InputParameters = m_InputSignature.size();
  1951. pDesc->OutputParameters = m_OutputSignature.size();
  1952. pDesc->PatchConstantParameters = m_PatchConstantSignature.size();
  1953. pDesc->GSOutputTopology = (D3D_PRIMITIVE_TOPOLOGY)M.GetStreamPrimitiveTopology();
  1954. pDesc->GSMaxOutputVertexCount = M.GetMaxVertexCount();
  1955. if (pSM->IsHS())
  1956. pDesc->InputPrimitive = (D3D_PRIMITIVE)(D3D_PRIMITIVE_1_CONTROL_POINT_PATCH + M.GetInputControlPointCount() - 1);
  1957. else
  1958. pDesc->InputPrimitive = (D3D_PRIMITIVE)M.GetInputPrimitive();
  1959. pDesc->cGSInstanceCount = M.GetGSInstanceCount();
  1960. if (pSM->IsHS())
  1961. pDesc->cControlPoints = M.GetOutputControlPointCount();
  1962. else if (pSM->IsDS())
  1963. pDesc->cControlPoints = M.GetInputControlPointCount();
  1964. pDesc->HSOutputPrimitive = (D3D_TESSELLATOR_OUTPUT_PRIMITIVE)M.GetTessellatorOutputPrimitive();
  1965. pDesc->HSPartitioning = (D3D_TESSELLATOR_PARTITIONING)M.GetTessellatorPartitioning();
  1966. pDesc->TessellatorDomain = (D3D_TESSELLATOR_DOMAIN)M.GetTessellatorDomain();
  1967. // Instruction counts only roughly track some fxc counters
  1968. DxilCounters counters = {};
  1969. m_pDxilModule->LoadDxilCounters(counters);
  1970. // UINT InstructionCount; // Num llvm instructions in all functions
  1971. // UINT TempArrayCount; // Number of bytes used in arrays (alloca + static global)
  1972. // UINT DynamicFlowControlCount; // Number of branches with more than one successor for now
  1973. // UINT ArrayInstructionCount; // number of load/store on arrays for now
  1974. pDesc->InstructionCount = counters.insts;
  1975. pDesc->TempArrayCount = counters.AllArrayBytes();
  1976. pDesc->DynamicFlowControlCount = counters.branches;
  1977. pDesc->ArrayInstructionCount = counters.AllArrayAccesses();
  1978. // UINT FloatInstructionCount; // Number of floating point arithmetic instructions used
  1979. // UINT IntInstructionCount; // Number of signed integer arithmetic instructions used
  1980. // UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used
  1981. pDesc->FloatInstructionCount = counters.floats;
  1982. pDesc->IntInstructionCount = counters.ints;
  1983. pDesc->UintInstructionCount = counters.uints;
  1984. // UINT TextureNormalInstructions; // Number of non-categorized texture instructions
  1985. // UINT TextureLoadInstructions; // Number of texture load instructions
  1986. // UINT TextureCompInstructions; // Number of texture comparison instructions
  1987. // UINT TextureBiasInstructions; // Number of texture bias instructions
  1988. // UINT TextureGradientInstructions; // Number of texture gradient instructions
  1989. pDesc->TextureNormalInstructions = counters.tex_norm;
  1990. pDesc->TextureLoadInstructions = counters.tex_load;
  1991. pDesc->TextureCompInstructions = counters.tex_cmp;
  1992. pDesc->TextureBiasInstructions = counters.tex_bias;
  1993. pDesc->TextureGradientInstructions = counters.tex_grad;
  1994. // UINT CutInstructionCount; // Number of cut instructions used
  1995. // UINT EmitInstructionCount; // Number of emit instructions used
  1996. pDesc->CutInstructionCount = counters.gs_cut;
  1997. pDesc->EmitInstructionCount = counters.gs_emit;
  1998. // UINT cBarrierInstructions; // Number of barrier instructions in a compute shader
  1999. // UINT cInterlockedInstructions; // Number of interlocked instructions
  2000. // UINT cTextureStoreInstructions; // Number of texture writes
  2001. pDesc->cBarrierInstructions = counters.barrier;
  2002. pDesc->cInterlockedInstructions = counters.atomic;
  2003. pDesc->cTextureStoreInstructions = counters.tex_store;
  2004. // Unset: UINT TempRegisterCount; // Don't know how to map this for SSA (not going to do reg allocation here)
  2005. // Unset: UINT DefCount; // Not sure what to map this to
  2006. // Unset: UINT DclCount; // Number of declarations (input + output)
  2007. // TODO: map to used input + output signature rows?
  2008. // Unset: UINT StaticFlowControlCount; // Number of static flow control instructions used
  2009. // This used to map to flow control using special int/bool constant registers in DX9.
  2010. // Unset: UINT MacroInstructionCount; // Number of macro instructions used
  2011. // Macro instructions are a <= DX9 concept.
  2012. }
  2013. _Use_decl_annotations_
  2014. ID3D12ShaderReflectionConstantBuffer* DxilShaderReflection::GetConstantBufferByIndex(UINT Index) {
  2015. return DxilModuleReflection::_GetConstantBufferByIndex(Index);
  2016. }
  2017. ID3D12ShaderReflectionConstantBuffer* DxilModuleReflection::_GetConstantBufferByIndex(UINT Index) {
  2018. if (Index >= m_CBs.size()) {
  2019. return &g_InvalidSRConstantBuffer;
  2020. }
  2021. return m_CBs[Index].get();
  2022. }
  2023. _Use_decl_annotations_
  2024. ID3D12ShaderReflectionConstantBuffer* DxilShaderReflection::GetConstantBufferByName(LPCSTR Name) {
  2025. return DxilModuleReflection::_GetConstantBufferByName(Name);
  2026. }
  2027. ID3D12ShaderReflectionConstantBuffer* DxilModuleReflection::_GetConstantBufferByName(LPCSTR Name) {
  2028. if (!Name) {
  2029. return &g_InvalidSRConstantBuffer;
  2030. }
  2031. size_t index = m_CBs.size();
  2032. auto it = m_CBsByName.find(Name);
  2033. if (it != m_CBsByName.end()) {
  2034. index = it->second;
  2035. } else {
  2036. it = m_StructuredBufferCBsByName.find(Name);
  2037. if (it != m_StructuredBufferCBsByName.end()) {
  2038. index = it->second;
  2039. }
  2040. }
  2041. if (index < m_CBs.size()) {
  2042. return m_CBs[index].get();
  2043. }
  2044. return &g_InvalidSRConstantBuffer;
  2045. }
  2046. _Use_decl_annotations_
  2047. HRESULT DxilShaderReflection::GetResourceBindingDesc(UINT ResourceIndex,
  2048. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc) {
  2049. return DxilModuleReflection::_GetResourceBindingDesc(ResourceIndex, pDesc, m_PublicAPI);
  2050. }
  2051. HRESULT DxilModuleReflection::_GetResourceBindingDesc(UINT ResourceIndex,
  2052. _Out_ D3D12_SHADER_INPUT_BIND_DESC *pDesc, PublicAPI api) {
  2053. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  2054. IFRBOOL(ResourceIndex < m_Resources.size(), E_INVALIDARG);
  2055. if (api != PublicAPI::D3D12) {
  2056. memcpy(pDesc, &m_Resources[ResourceIndex], sizeof(D3D11_SHADER_INPUT_BIND_DESC));
  2057. }
  2058. else {
  2059. *pDesc = m_Resources[ResourceIndex];
  2060. }
  2061. return S_OK;
  2062. }
  2063. _Use_decl_annotations_
  2064. HRESULT DxilShaderReflection::GetInputParameterDesc(UINT ParameterIndex,
  2065. _Out_ D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  2066. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  2067. IFRBOOL(ParameterIndex < m_InputSignature.size(), E_INVALIDARG);
  2068. if (m_PublicAPI != PublicAPI::D3D11_43)
  2069. *pDesc = m_InputSignature[ParameterIndex];
  2070. else
  2071. memcpy(pDesc, &m_InputSignature[ParameterIndex],
  2072. // D3D11_43 does not have MinPrecison.
  2073. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  2074. return S_OK;
  2075. }
  2076. _Use_decl_annotations_
  2077. HRESULT DxilShaderReflection::GetOutputParameterDesc(UINT ParameterIndex,
  2078. D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  2079. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  2080. IFRBOOL(ParameterIndex < m_OutputSignature.size(), E_INVALIDARG);
  2081. if (m_PublicAPI != PublicAPI::D3D11_43)
  2082. *pDesc = m_OutputSignature[ParameterIndex];
  2083. else
  2084. memcpy(pDesc, &m_OutputSignature[ParameterIndex],
  2085. // D3D11_43 does not have MinPrecison.
  2086. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  2087. return S_OK;
  2088. }
  2089. _Use_decl_annotations_
  2090. HRESULT DxilShaderReflection::GetPatchConstantParameterDesc(UINT ParameterIndex,
  2091. D3D12_SIGNATURE_PARAMETER_DESC *pDesc) {
  2092. IFRBOOL(pDesc != nullptr, E_INVALIDARG);
  2093. IFRBOOL(ParameterIndex < m_PatchConstantSignature.size(), E_INVALIDARG);
  2094. if (m_PublicAPI != PublicAPI::D3D11_43)
  2095. *pDesc = m_PatchConstantSignature[ParameterIndex];
  2096. else
  2097. memcpy(pDesc, &m_PatchConstantSignature[ParameterIndex],
  2098. // D3D11_43 does not have MinPrecison.
  2099. sizeof(D3D12_SIGNATURE_PARAMETER_DESC) - sizeof(D3D_MIN_PRECISION));
  2100. return S_OK;
  2101. }
  2102. _Use_decl_annotations_
  2103. ID3D12ShaderReflectionVariable* DxilShaderReflection::GetVariableByName(LPCSTR Name) {
  2104. return DxilModuleReflection::_GetVariableByName(Name);
  2105. }
  2106. ID3D12ShaderReflectionVariable* DxilModuleReflection::_GetVariableByName(LPCSTR Name) {
  2107. if (Name != nullptr) {
  2108. // Iterate through all cbuffers to find the variable.
  2109. for (UINT i = 0; i < m_CBs.size(); i++) {
  2110. ID3D12ShaderReflectionVariable *pVar = m_CBs[i]->GetVariableByName(Name);
  2111. if (pVar != &g_InvalidSRVariable) {
  2112. return pVar;
  2113. }
  2114. }
  2115. }
  2116. return &g_InvalidSRVariable;
  2117. }
  2118. _Use_decl_annotations_
  2119. HRESULT DxilShaderReflection::GetResourceBindingDescByName(LPCSTR Name,
  2120. D3D12_SHADER_INPUT_BIND_DESC *pDesc) {
  2121. return DxilModuleReflection::_GetResourceBindingDescByName(Name, pDesc, m_PublicAPI);
  2122. }
  2123. HRESULT DxilModuleReflection::_GetResourceBindingDescByName(LPCSTR Name,
  2124. D3D12_SHADER_INPUT_BIND_DESC *pDesc, PublicAPI api) {
  2125. IFRBOOL(Name != nullptr, E_INVALIDARG);
  2126. for (UINT i = 0; i < m_Resources.size(); i++) {
  2127. if (strcmp(m_Resources[i].Name, Name) == 0) {
  2128. if (api != PublicAPI::D3D12) {
  2129. memcpy(pDesc, &m_Resources[i], sizeof(D3D11_SHADER_INPUT_BIND_DESC));
  2130. }
  2131. else {
  2132. *pDesc = m_Resources[i];
  2133. }
  2134. return S_OK;
  2135. }
  2136. }
  2137. return HRESULT_FROM_WIN32(ERROR_NOT_FOUND);
  2138. }
  2139. UINT DxilShaderReflection::GetMovInstructionCount() { return 0; }
  2140. UINT DxilShaderReflection::GetMovcInstructionCount() { return 0; }
  2141. UINT DxilShaderReflection::GetConversionInstructionCount() { return 0; }
  2142. UINT DxilShaderReflection::GetBitwiseInstructionCount() { return 0; }
  2143. D3D_PRIMITIVE DxilShaderReflection::GetGSInputPrimitive() {
  2144. if (!m_pDxilModule->GetShaderModel()->IsGS())
  2145. return D3D_PRIMITIVE::D3D10_PRIMITIVE_UNDEFINED;
  2146. return (D3D_PRIMITIVE)m_pDxilModule->GetInputPrimitive();
  2147. }
  2148. BOOL DxilShaderReflection::IsSampleFrequencyShader() {
  2149. // TODO: determine correct value
  2150. return FALSE;
  2151. }
  2152. UINT DxilShaderReflection::GetNumInterfaceSlots() { return 0; }
  2153. _Use_decl_annotations_
  2154. HRESULT DxilShaderReflection::GetMinFeatureLevel(enum D3D_FEATURE_LEVEL* pLevel) {
  2155. IFR(AssignToOut(D3D_FEATURE_LEVEL_12_0, pLevel));
  2156. return S_OK;
  2157. }
  2158. _Use_decl_annotations_
  2159. UINT DxilShaderReflection::GetThreadGroupSize(UINT *pSizeX, UINT *pSizeY, UINT *pSizeZ) {
  2160. if (!m_pDxilModule->GetShaderModel()->IsCS()) {
  2161. AssignToOutOpt((UINT)0, pSizeX);
  2162. AssignToOutOpt((UINT)0, pSizeY);
  2163. AssignToOutOpt((UINT)0, pSizeZ);
  2164. return 0;
  2165. }
  2166. unsigned x = m_pDxilModule->GetNumThreads(0);
  2167. unsigned y = m_pDxilModule->GetNumThreads(1);
  2168. unsigned z = m_pDxilModule->GetNumThreads(2);
  2169. AssignToOutOpt(x, pSizeX);
  2170. AssignToOutOpt(y, pSizeY);
  2171. AssignToOutOpt(z, pSizeZ);
  2172. return x * y * z;
  2173. }
  2174. UINT64 DxilShaderReflection::GetRequiresFlags() {
  2175. UINT64 result = m_pDxilModule->m_ShaderFlags.GetFeatureInfo();
  2176. // FeatureInfo flags are identical, with the exception of a collision between:
  2177. // SHADER_FEATURE_COMPUTE_SHADERS_PLUS_RAW_AND_STRUCTURED_BUFFERS_VIA_SHADER_4_X
  2178. // and D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL
  2179. // We keep track of the flag elsewhere, so use that instead.
  2180. result &= ~(UINT64)D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL;
  2181. if (m_pDxilModule->m_ShaderFlags.GetForceEarlyDepthStencil())
  2182. result |= D3D_SHADER_REQUIRES_EARLY_DEPTH_STENCIL;
  2183. return result;
  2184. }
  2185. // ID3D12FunctionReflection
  2186. class CFunctionReflection : public ID3D12FunctionReflection {
  2187. protected:
  2188. DxilLibraryReflection * m_pLibraryReflection = nullptr;
  2189. const Function *m_pFunction;
  2190. const DxilFunctionProps *m_pProps; // nullptr if non-shader library function or patch constant function
  2191. std::string m_Name;
  2192. typedef SmallSetVector<UINT32, 8> ResourceUseSet;
  2193. ResourceUseSet m_UsedResources;
  2194. ResourceUseSet m_UsedCBs;
  2195. public:
  2196. void Initialize(DxilLibraryReflection* pLibraryReflection, Function *pFunction) {
  2197. DXASSERT_NOMSG(pLibraryReflection);
  2198. DXASSERT_NOMSG(pFunction);
  2199. m_pLibraryReflection = pLibraryReflection;
  2200. m_pFunction = pFunction;
  2201. const DxilModule &M = *m_pLibraryReflection->m_pDxilModule;
  2202. m_Name = m_pFunction->getName().str();
  2203. m_pProps = nullptr;
  2204. if (M.HasDxilFunctionProps(m_pFunction)) {
  2205. m_pProps = &M.GetDxilFunctionProps(m_pFunction);
  2206. }
  2207. }
  2208. void AddResourceReference(UINT resIndex) {
  2209. m_UsedResources.insert(resIndex);
  2210. }
  2211. void AddCBReference(UINT cbIndex) {
  2212. m_UsedCBs.insert(cbIndex);
  2213. }
  2214. // ID3D12FunctionReflection
  2215. STDMETHOD(GetDesc)(THIS_ _Out_ D3D12_FUNCTION_DESC * pDesc);
  2216. // BufferIndex relative to used constant buffers here
  2217. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByIndex)(THIS_ _In_ UINT BufferIndex);
  2218. STDMETHOD_(ID3D12ShaderReflectionConstantBuffer *, GetConstantBufferByName)(THIS_ _In_ LPCSTR Name);
  2219. STDMETHOD(GetResourceBindingDesc)(THIS_ _In_ UINT ResourceIndex,
  2220. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc);
  2221. STDMETHOD_(ID3D12ShaderReflectionVariable *, GetVariableByName)(THIS_ _In_ LPCSTR Name);
  2222. STDMETHOD(GetResourceBindingDescByName)(THIS_ _In_ LPCSTR Name,
  2223. _Out_ D3D12_SHADER_INPUT_BIND_DESC * pDesc);
  2224. // Use D3D_RETURN_PARAMETER_INDEX to get description of the return value.
  2225. STDMETHOD_(ID3D12FunctionParameterReflection *, GetFunctionParameter)(THIS_ _In_ INT ParameterIndex) {
  2226. return &g_InvalidFunctionParameter;
  2227. }
  2228. };
  2229. _Use_decl_annotations_
  2230. HRESULT CFunctionReflection::GetDesc(D3D12_FUNCTION_DESC *pDesc) {
  2231. DXASSERT_NOMSG(m_pLibraryReflection);
  2232. IFR(ZeroMemoryToOut(pDesc));
  2233. const ShaderModel* pSM = m_pLibraryReflection->m_pDxilModule->GetShaderModel();
  2234. DXIL::ShaderKind kind = DXIL::ShaderKind::Library;
  2235. if (m_pProps) {
  2236. kind = m_pProps->shaderKind;
  2237. }
  2238. pDesc->Version = EncodeVersion(kind, pSM->GetMajor(), pSM->GetMinor());
  2239. //Unset: LPCSTR Creator; // Creator string
  2240. //Unset: UINT Flags; // Shader compilation/parse flags
  2241. pDesc->ConstantBuffers = (UINT)m_UsedCBs.size();
  2242. pDesc->BoundResources = (UINT)m_UsedResources.size();
  2243. //Unset: UINT InstructionCount; // Number of emitted instructions
  2244. //Unset: UINT TempRegisterCount; // Number of temporary registers used
  2245. //Unset: UINT TempArrayCount; // Number of temporary arrays used
  2246. //Unset: UINT DefCount; // Number of constant defines
  2247. //Unset: UINT DclCount; // Number of declarations (input + output)
  2248. //Unset: UINT TextureNormalInstructions; // Number of non-categorized texture instructions
  2249. //Unset: UINT TextureLoadInstructions; // Number of texture load instructions
  2250. //Unset: UINT TextureCompInstructions; // Number of texture comparison instructions
  2251. //Unset: UINT TextureBiasInstructions; // Number of texture bias instructions
  2252. //Unset: UINT TextureGradientInstructions; // Number of texture gradient instructions
  2253. //Unset: UINT FloatInstructionCount; // Number of floating point arithmetic instructions used
  2254. //Unset: UINT IntInstructionCount; // Number of signed integer arithmetic instructions used
  2255. //Unset: UINT UintInstructionCount; // Number of unsigned integer arithmetic instructions used
  2256. //Unset: UINT StaticFlowControlCount; // Number of static flow control instructions used
  2257. //Unset: UINT DynamicFlowControlCount; // Number of dynamic flow control instructions used
  2258. //Unset: UINT MacroInstructionCount; // Number of macro instructions used
  2259. //Unset: UINT ArrayInstructionCount; // Number of array instructions used
  2260. //Unset: UINT MovInstructionCount; // Number of mov instructions used
  2261. //Unset: UINT MovcInstructionCount; // Number of movc instructions used
  2262. //Unset: UINT ConversionInstructionCount; // Number of type conversion instructions used
  2263. //Unset: UINT BitwiseInstructionCount; // Number of bitwise arithmetic instructions used
  2264. //Unset: D3D_FEATURE_LEVEL MinFeatureLevel; // Min target of the function byte code
  2265. //Unset: UINT64 RequiredFeatureFlags; // Required feature flags
  2266. pDesc->Name = m_Name.c_str();
  2267. //Unset: INT FunctionParameterCount; // Number of logical parameters in the function signature (not including return)
  2268. //Unset: BOOL HasReturn; // TRUE, if function returns a value, false - it is a subroutine
  2269. //Unset: BOOL Has10Level9VertexShader; // TRUE, if there is a 10L9 VS blob
  2270. //Unset: BOOL Has10Level9PixelShader; // TRUE, if there is a 10L9 PS blob
  2271. return S_OK;
  2272. }
  2273. // BufferIndex is relative to used constant buffers here
  2274. ID3D12ShaderReflectionConstantBuffer *CFunctionReflection::GetConstantBufferByIndex(UINT BufferIndex) {
  2275. DXASSERT_NOMSG(m_pLibraryReflection);
  2276. if (BufferIndex >= m_UsedCBs.size())
  2277. return &g_InvalidSRConstantBuffer;
  2278. return m_pLibraryReflection->_GetConstantBufferByIndex(m_UsedCBs[BufferIndex]);
  2279. }
  2280. ID3D12ShaderReflectionConstantBuffer *CFunctionReflection::GetConstantBufferByName(LPCSTR Name) {
  2281. DXASSERT_NOMSG(m_pLibraryReflection);
  2282. return m_pLibraryReflection->_GetConstantBufferByName(Name);
  2283. }
  2284. HRESULT CFunctionReflection::GetResourceBindingDesc(UINT ResourceIndex,
  2285. D3D12_SHADER_INPUT_BIND_DESC * pDesc) {
  2286. DXASSERT_NOMSG(m_pLibraryReflection);
  2287. if (ResourceIndex >= m_UsedResources.size())
  2288. return E_INVALIDARG;
  2289. return m_pLibraryReflection->_GetResourceBindingDesc(m_UsedResources[ResourceIndex], pDesc);
  2290. }
  2291. ID3D12ShaderReflectionVariable * CFunctionReflection::GetVariableByName(LPCSTR Name) {
  2292. DXASSERT_NOMSG(m_pLibraryReflection);
  2293. return m_pLibraryReflection->_GetVariableByName(Name);
  2294. }
  2295. HRESULT CFunctionReflection::GetResourceBindingDescByName(LPCSTR Name,
  2296. D3D12_SHADER_INPUT_BIND_DESC * pDesc) {
  2297. DXASSERT_NOMSG(m_pLibraryReflection);
  2298. return m_pLibraryReflection->_GetResourceBindingDescByName(Name, pDesc);
  2299. }
  2300. // DxilLibraryReflection
  2301. void DxilLibraryReflection::AddResourceDependencies() {
  2302. RDAT::FunctionTableReader *functionTable = m_RDAT.GetFunctionTableReader();
  2303. m_FunctionVector.clear();
  2304. m_FunctionVector.reserve(functionTable->GetNumFunctions());
  2305. std::map<StringRef, CFunctionReflection*> orderedMap;
  2306. RDAT::ResourceTableReader *resourceTable = m_RDAT.GetResourceTableReader();
  2307. unsigned SamplersStart = resourceTable->GetNumCBuffers();
  2308. unsigned SRVsStart = SamplersStart + resourceTable->GetNumSamplers();
  2309. unsigned UAVsStart = SRVsStart + resourceTable->GetNumSRVs();
  2310. IFTBOOL(resourceTable->GetNumResources() == m_Resources.size(),
  2311. DXC_E_INCORRECT_DXIL_METADATA);
  2312. for (unsigned iFunc = 0; iFunc < functionTable->GetNumFunctions(); ++iFunc) {
  2313. RDAT::FunctionReader FR = functionTable->GetItem(iFunc);
  2314. auto &func = m_FunctionMap[FR.GetName()];
  2315. DXASSERT(!func.get(), "otherwise duplicate named functions");
  2316. Function *F = m_pModule->getFunction(FR.GetName());
  2317. func.reset(new CFunctionReflection());
  2318. func->Initialize(this, F);
  2319. m_FunctionsByPtr[F] = func.get();
  2320. orderedMap[FR.GetName()] = func.get();
  2321. for (unsigned iRes = 0; iRes < FR.GetNumResources(); ++iRes) {
  2322. RDAT::ResourceReader RR = FR.GetResource(iRes);
  2323. unsigned id = RR.GetID();
  2324. switch (RR.GetResourceClass()) {
  2325. case DXIL::ResourceClass::CBuffer:
  2326. func->AddResourceReference(id);
  2327. func->AddCBReference(id);
  2328. break;
  2329. case DXIL::ResourceClass::Sampler:
  2330. func->AddResourceReference(SamplersStart + id);
  2331. break;
  2332. case DXIL::ResourceClass::SRV:
  2333. func->AddResourceReference(SRVsStart + id);
  2334. if (DXIL::IsStructuredBuffer(RR.GetResourceKind())) {
  2335. auto it = m_StructuredBufferCBsByName.find(RR.GetName());
  2336. if (it != m_StructuredBufferCBsByName.end())
  2337. func->AddCBReference(it->second);
  2338. } else if (RR.GetResourceKind() == DXIL::ResourceKind::TBuffer) {
  2339. auto it = m_CBsByName.find(RR.GetName());
  2340. if (it != m_CBsByName.end())
  2341. func->AddCBReference(it->second);
  2342. }
  2343. break;
  2344. case DXIL::ResourceClass::UAV:
  2345. func->AddResourceReference(UAVsStart + id);
  2346. if (DXIL::IsStructuredBuffer(RR.GetResourceKind())) {
  2347. auto it = m_StructuredBufferCBsByName.find(RR.GetName());
  2348. if (it != m_StructuredBufferCBsByName.end())
  2349. func->AddCBReference(it->second);
  2350. }
  2351. break;
  2352. default:
  2353. DXASSERT(false, "Unrecognized ResourceClass in RDAT");
  2354. }
  2355. }
  2356. }
  2357. for (auto &it : orderedMap) {
  2358. m_FunctionVector.push_back(it.second);
  2359. }
  2360. }
  2361. static void CollectCBufUsageForLib(Value *V, std::vector<unsigned> &cbufUsage, bool bMinPrecision) {
  2362. for (auto user : V->users()) {
  2363. Value *V = user;
  2364. if (auto *CI = dyn_cast<CallInst>(V)) {
  2365. if (hlsl::OP::IsDxilOpFuncCallInst(CI, hlsl::OP::OpCode::CreateHandleForLib)) {
  2366. CollectCBufUsage(CI, cbufUsage, bMinPrecision);
  2367. }
  2368. } else if (isa<GEPOperator>(V) ||
  2369. isa<LoadInst>(V)) {
  2370. CollectCBufUsageForLib(user, cbufUsage, bMinPrecision);
  2371. }
  2372. }
  2373. }
  2374. void DxilLibraryReflection::SetCBufferUsage() {
  2375. unsigned cbSize = std::min(m_CBs.size(), m_pDxilModule->GetCBuffers().size());
  2376. for (unsigned i=0;i<cbSize;i++) {
  2377. std::vector<unsigned> cbufUsage;
  2378. CollectCBufUsageForLib(m_pDxilModule->GetCBuffer(i).GetGlobalSymbol(), cbufUsage, m_pDxilModule->GetUseMinPrecision());
  2379. SetCBufVarUsage(*m_CBs[i], cbufUsage);
  2380. }
  2381. }
  2382. // ID3D12LibraryReflection
  2383. HRESULT DxilLibraryReflection::Load(const DxilPartHeader *pModulePart,
  2384. const DxilPartHeader *pRDATPart) {
  2385. IFR(LoadRDAT(pRDATPart));
  2386. IFR(LoadModule(pModulePart));
  2387. try {
  2388. AddResourceDependencies();
  2389. if (!m_bUsageInMetadata)
  2390. SetCBufferUsage();
  2391. return S_OK;
  2392. }
  2393. CATCH_CPP_RETURN_HRESULT();
  2394. }
  2395. _Use_decl_annotations_
  2396. HRESULT DxilLibraryReflection::GetDesc(D3D12_LIBRARY_DESC * pDesc) {
  2397. IFR(ZeroMemoryToOut(pDesc));
  2398. //Unset: LPCSTR Creator; // The name of the originator of the library.
  2399. //Unset: UINT Flags; // Compilation flags.
  2400. //UINT FunctionCount; // Number of functions exported from the library.
  2401. pDesc->FunctionCount = (UINT)m_FunctionVector.size();
  2402. return S_OK;
  2403. }
  2404. _Use_decl_annotations_
  2405. ID3D12FunctionReflection *DxilLibraryReflection::GetFunctionByIndex(INT FunctionIndex) {
  2406. if ((UINT)FunctionIndex >= m_FunctionVector.size())
  2407. return &g_InvalidFunction;
  2408. return m_FunctionVector[FunctionIndex];
  2409. }
  2410. #else // LLVM_ON_WIN32
  2411. void hlsl::CreateDxcContainerReflection(IDxcContainerReflection **ppResult) {
  2412. *ppResult = nullptr;
  2413. }
  2414. #endif // LLVM_ON_WIN32