DxilContainerReflection.cpp 101 KB

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