DxilContainerReflection.cpp 101 KB

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