DxilModule.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // //
  3. // DxilModule.h //
  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. // The main class to work with DXIL, similar to LLVM module. //
  9. // //
  10. ///////////////////////////////////////////////////////////////////////////////
  11. #pragma once
  12. #include "dxc/DXIL/DxilConstants.h"
  13. #include "dxc/DXIL/DxilMetadataHelper.h"
  14. #include "dxc/DXIL/DxilCBuffer.h"
  15. #include "dxc/DXIL/DxilResource.h"
  16. #include "dxc/DXIL/DxilSampler.h"
  17. #include "dxc/DXIL/DxilShaderFlags.h"
  18. #include "dxc/DXIL/DxilSignature.h"
  19. #include "dxc/DXIL/DxilSubobject.h"
  20. #include "dxc/DXIL/DxilTypeSystem.h"
  21. #include <memory>
  22. #include <string>
  23. #include <vector>
  24. #include <unordered_map>
  25. #include <unordered_set>
  26. namespace llvm {
  27. class LLVMContext;
  28. class Module;
  29. class Function;
  30. class Instruction;
  31. class MDTuple;
  32. class MDOperand;
  33. class DebugInfoFinder;
  34. }
  35. namespace hlsl {
  36. class ShaderModel;
  37. class OP;
  38. struct DxilFunctionProps;
  39. class DxilEntryProps;
  40. using DxilEntryPropsMap =
  41. std::unordered_map<const llvm::Function *, std::unique_ptr<DxilEntryProps>>;
  42. /// Use this class to manipulate DXIL of a shader.
  43. class DxilModule {
  44. public:
  45. DxilModule(llvm::Module *pModule);
  46. ~DxilModule();
  47. // Subsystems.
  48. llvm::LLVMContext &GetCtx() const;
  49. llvm::Module *GetModule() const;
  50. OP *GetOP() const;
  51. void SetShaderModel(const ShaderModel *pSM, bool bUseMinPrecision = true);
  52. const ShaderModel *GetShaderModel() const;
  53. void GetDxilVersion(unsigned &DxilMajor, unsigned &DxilMinor) const;
  54. void SetValidatorVersion(unsigned ValMajor, unsigned ValMinor);
  55. bool UpgradeValidatorVersion(unsigned ValMajor, unsigned ValMinor);
  56. void GetValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const;
  57. // Return true on success, requires valid shader model and CollectShaderFlags to have been set
  58. bool GetMinValidatorVersion(unsigned &ValMajor, unsigned &ValMinor) const;
  59. // Update validator version to minimum if higher than current (ex: after CollectShaderFlags)
  60. bool UpgradeToMinValidatorVersion();
  61. // Entry functions.
  62. llvm::Function *GetEntryFunction();
  63. const llvm::Function *GetEntryFunction() const;
  64. void SetEntryFunction(llvm::Function *pEntryFunc);
  65. const std::string &GetEntryFunctionName() const;
  66. void SetEntryFunctionName(const std::string &name);
  67. llvm::Function *GetPatchConstantFunction();
  68. const llvm::Function *GetPatchConstantFunction() const;
  69. void SetPatchConstantFunction(llvm::Function *pFunc);
  70. bool IsEntryOrPatchConstantFunction(const llvm::Function* pFunc) const;
  71. // Flags.
  72. unsigned GetGlobalFlags() const;
  73. void CollectShaderFlagsForModule();
  74. // Resources.
  75. unsigned AddCBuffer(std::unique_ptr<DxilCBuffer> pCB);
  76. DxilCBuffer &GetCBuffer(unsigned idx);
  77. const DxilCBuffer &GetCBuffer(unsigned idx) const;
  78. const std::vector<std::unique_ptr<DxilCBuffer> > &GetCBuffers() const;
  79. unsigned AddSampler(std::unique_ptr<DxilSampler> pSampler);
  80. DxilSampler &GetSampler(unsigned idx);
  81. const DxilSampler &GetSampler(unsigned idx) const;
  82. const std::vector<std::unique_ptr<DxilSampler> > &GetSamplers() const;
  83. unsigned AddSRV(std::unique_ptr<DxilResource> pSRV);
  84. DxilResource &GetSRV(unsigned idx);
  85. const DxilResource &GetSRV(unsigned idx) const;
  86. const std::vector<std::unique_ptr<DxilResource> > &GetSRVs() const;
  87. unsigned AddUAV(std::unique_ptr<DxilResource> pUAV);
  88. DxilResource &GetUAV(unsigned idx);
  89. const DxilResource &GetUAV(unsigned idx) const;
  90. const std::vector<std::unique_ptr<DxilResource> > &GetUAVs() const;
  91. void LoadDxilResourceBaseFromMDNode(llvm::MDNode *MD, DxilResourceBase &R);
  92. void LoadDxilResourceFromMDNode(llvm::MDNode *MD, DxilResource &R);
  93. void LoadDxilSamplerFromMDNode(llvm::MDNode *MD, DxilSampler &S);
  94. void RemoveUnusedResources();
  95. void RemoveResourcesWithUnusedSymbols();
  96. void RemoveFunction(llvm::Function *F);
  97. // Signatures.
  98. DxilSignature &GetInputSignature();
  99. const DxilSignature &GetInputSignature() const;
  100. DxilSignature &GetOutputSignature();
  101. const DxilSignature &GetOutputSignature() const;
  102. DxilSignature &GetPatchConstOrPrimSignature();
  103. const DxilSignature &GetPatchConstOrPrimSignature() const;
  104. const std::vector<uint8_t> &GetSerializedRootSignature() const;
  105. std::vector<uint8_t> &GetSerializedRootSignature();
  106. bool HasDxilEntrySignature(const llvm::Function *F) const;
  107. DxilEntrySignature &GetDxilEntrySignature(const llvm::Function *F);
  108. // Move DxilEntryProps of F to NewF.
  109. void ReplaceDxilEntryProps(llvm::Function *F, llvm::Function *NewF);
  110. // Clone DxilEntryProps of F to NewF.
  111. void CloneDxilEntryProps(llvm::Function *F, llvm::Function *NewF);
  112. bool HasDxilEntryProps(const llvm::Function *F) const;
  113. DxilEntryProps &GetDxilEntryProps(const llvm::Function *F);
  114. const DxilEntryProps &GetDxilEntryProps(const llvm::Function *F) const;
  115. // DxilFunctionProps.
  116. bool HasDxilFunctionProps(const llvm::Function *F) const;
  117. DxilFunctionProps &GetDxilFunctionProps(const llvm::Function *F);
  118. const DxilFunctionProps &GetDxilFunctionProps(const llvm::Function *F) const;
  119. // Move DxilFunctionProps of F to NewF.
  120. void SetPatchConstantFunctionForHS(llvm::Function *hullShaderFunc, llvm::Function *patchConstantFunc);
  121. bool IsGraphicsShader(const llvm::Function *F) const; // vs,hs,ds,gs,ps
  122. bool IsPatchConstantShader(const llvm::Function *F) const;
  123. bool IsComputeShader(const llvm::Function *F) const;
  124. // Is an entry function that uses input/output signature conventions?
  125. // Includes: vs/hs/ds/gs/ps/cs as well as the patch constant function.
  126. bool IsEntryThatUsesSignatures(const llvm::Function *F) const ;
  127. // Remove Root Signature from module metadata, return true if changed
  128. bool StripRootSignatureFromMetadata();
  129. // Remove Subobjects from module metadata, return true if changed
  130. bool StripSubobjectsFromMetadata();
  131. // Update validator version metadata to current setting
  132. void UpdateValidatorVersionMetadata();
  133. // DXIL type system.
  134. DxilTypeSystem &GetTypeSystem();
  135. /// Emit llvm.used array to make sure that optimizations do not remove unreferenced globals.
  136. void EmitLLVMUsed();
  137. std::vector<llvm::GlobalVariable* > &GetLLVMUsed();
  138. void ClearLLVMUsed();
  139. // ViewId state.
  140. std::vector<unsigned> &GetSerializedViewIdState();
  141. const std::vector<unsigned> &GetSerializedViewIdState() const;
  142. // DXIL metadata manipulation.
  143. /// Clear all DXIL data that exists in in-memory form.
  144. static void ClearDxilMetadata(llvm::Module &M);
  145. /// Serialize DXIL in-memory form to metadata form.
  146. void EmitDxilMetadata();
  147. /// Update resource metadata.
  148. /// Note: this method not update Metadata for ViewIdState.
  149. void ReEmitDxilResources();
  150. /// Deserialize DXIL metadata form into in-memory form.
  151. void LoadDxilMetadata();
  152. /// Return true if non-fatal metadata error was detected.
  153. bool HasMetadataErrors();
  154. /// Check if a Named meta data node is known by dxil module.
  155. static bool IsKnownNamedMetaData(llvm::NamedMDNode &Node);
  156. // Reset functions used to transfer ownership.
  157. void ResetEntrySignature(DxilEntrySignature *pValue);
  158. void ResetSerializedRootSignature(std::vector<uint8_t> &Value);
  159. void ResetTypeSystem(DxilTypeSystem *pValue);
  160. void ResetOP(hlsl::OP *hlslOP);
  161. void ResetEntryPropsMap(DxilEntryPropsMap &&PropMap);
  162. bool StripReflection();
  163. void StripDebugRelatedCode();
  164. llvm::DebugInfoFinder &GetOrCreateDebugInfoFinder();
  165. static DxilModule *TryGetDxilModule(llvm::Module *pModule);
  166. // Helpers for working with precise.
  167. // Return true if the instruction should be considered precise.
  168. //
  169. // An instruction can be marked precise in the following ways:
  170. //
  171. // 1. Global refactoring is disabled.
  172. // 2. The instruction has a precise metadata annotation.
  173. // 3. The instruction has precise fast math flags set.
  174. //
  175. bool IsPrecise(const llvm::Instruction *inst) const;
  176. // Check if the instruction has fast math flags configured to indicate
  177. // the instruction is precise.
  178. static bool HasPreciseFastMathFlags(const llvm::Instruction *inst);
  179. // Set fast math flags configured to indicate the instruction is precise.
  180. static void SetPreciseFastMathFlags(llvm::Instruction *inst);
  181. // True if fast math flags are preserved across serialize/deserialize.
  182. static bool PreservesFastMathFlags(const llvm::Instruction *inst);
  183. public:
  184. ShaderFlags m_ShaderFlags;
  185. void CollectShaderFlagsForModule(ShaderFlags &Flags);
  186. // Check if DxilModule contains multi component UAV Loads.
  187. // This funciton must be called after unused resources are removed from DxilModule
  188. bool ModuleHasMulticomponentUAVLoads();
  189. // Compute/Mesh/Amplification shader.
  190. void SetNumThreads(unsigned x, unsigned y, unsigned z);
  191. unsigned GetNumThreads(unsigned idx) const;
  192. // Geometry shader.
  193. DXIL::InputPrimitive GetInputPrimitive() const;
  194. void SetInputPrimitive(DXIL::InputPrimitive IP);
  195. unsigned GetMaxVertexCount() const;
  196. void SetMaxVertexCount(unsigned Count);
  197. DXIL::PrimitiveTopology GetStreamPrimitiveTopology() const;
  198. void SetStreamPrimitiveTopology(DXIL::PrimitiveTopology Topology);
  199. bool HasMultipleOutputStreams() const;
  200. unsigned GetOutputStream() const;
  201. unsigned GetGSInstanceCount() const;
  202. void SetGSInstanceCount(unsigned Count);
  203. bool IsStreamActive(unsigned Stream) const;
  204. void SetStreamActive(unsigned Stream, bool bActive);
  205. void SetActiveStreamMask(unsigned Mask);
  206. unsigned GetActiveStreamMask() const;
  207. // Language options
  208. // UseMinPrecision must be set at SetShaderModel time.
  209. bool GetUseMinPrecision() const;
  210. void SetDisableOptimization(bool disableOptimization);
  211. bool GetDisableOptimization() const;
  212. void SetAllResourcesBound(bool resourcesBound);
  213. bool GetAllResourcesBound() const;
  214. // Intermediate options that do not make it to DXIL
  215. void SetLegacyResourceReservation(bool legacyResourceReservation);
  216. bool GetLegacyResourceReservation() const;
  217. void ClearIntermediateOptions();
  218. // Hull and Domain shaders.
  219. unsigned GetInputControlPointCount() const;
  220. void SetInputControlPointCount(unsigned NumICPs);
  221. DXIL::TessellatorDomain GetTessellatorDomain() const;
  222. void SetTessellatorDomain(DXIL::TessellatorDomain TessDomain);
  223. // Hull shader.
  224. unsigned GetOutputControlPointCount() const;
  225. void SetOutputControlPointCount(unsigned NumOCPs);
  226. DXIL::TessellatorPartitioning GetTessellatorPartitioning() const;
  227. void SetTessellatorPartitioning(DXIL::TessellatorPartitioning TessPartitioning);
  228. DXIL::TessellatorOutputPrimitive GetTessellatorOutputPrimitive() const;
  229. void SetTessellatorOutputPrimitive(DXIL::TessellatorOutputPrimitive TessOutputPrimitive);
  230. float GetMaxTessellationFactor() const;
  231. void SetMaxTessellationFactor(float MaxTessellationFactor);
  232. // Mesh shader
  233. unsigned GetMaxOutputVertices() const;
  234. void SetMaxOutputVertices(unsigned NumOVs);
  235. unsigned GetMaxOutputPrimitives() const;
  236. void SetMaxOutputPrimitives(unsigned NumOPs);
  237. DXIL::MeshOutputTopology GetMeshOutputTopology() const;
  238. void SetMeshOutputTopology(DXIL::MeshOutputTopology MeshOutputTopology);
  239. unsigned GetPayloadSizeInBytes() const;
  240. void SetPayloadSizeInBytes(unsigned Size);
  241. // AutoBindingSpace also enables automatic binding for libraries if set.
  242. // UINT_MAX == unset
  243. void SetAutoBindingSpace(uint32_t Space);
  244. uint32_t GetAutoBindingSpace() const;
  245. void SetShaderProperties(DxilFunctionProps *props);
  246. DxilSubobjects *GetSubobjects();
  247. const DxilSubobjects *GetSubobjects() const;
  248. DxilSubobjects *ReleaseSubobjects();
  249. void ResetSubobjects(DxilSubobjects *subobjects);
  250. private:
  251. // Signatures.
  252. std::vector<uint8_t> m_SerializedRootSignature;
  253. // Shader resources.
  254. std::vector<std::unique_ptr<DxilResource> > m_SRVs;
  255. std::vector<std::unique_ptr<DxilResource> > m_UAVs;
  256. std::vector<std::unique_ptr<DxilCBuffer> > m_CBuffers;
  257. std::vector<std::unique_ptr<DxilSampler> > m_Samplers;
  258. // Geometry shader.
  259. DXIL::PrimitiveTopology m_StreamPrimitiveTopology;
  260. unsigned m_ActiveStreamMask;
  261. private:
  262. enum IntermediateFlags : uint32_t {
  263. LegacyResourceReservation = 1 << 0,
  264. };
  265. private:
  266. llvm::LLVMContext &m_Ctx;
  267. llvm::Module *m_pModule;
  268. llvm::Function *m_pEntryFunc;
  269. std::string m_EntryName;
  270. std::unique_ptr<DxilMDHelper> m_pMDHelper;
  271. std::unique_ptr<llvm::DebugInfoFinder> m_pDebugInfoFinder;
  272. const ShaderModel *m_pSM;
  273. unsigned m_DxilMajor;
  274. unsigned m_DxilMinor;
  275. unsigned m_ValMajor;
  276. unsigned m_ValMinor;
  277. std::unique_ptr<OP> m_pOP;
  278. size_t m_pUnused;
  279. // LLVM used.
  280. std::vector<llvm::GlobalVariable*> m_LLVMUsed;
  281. // Type annotations.
  282. std::unique_ptr<DxilTypeSystem> m_pTypeSystem;
  283. // EntryProps for shader functions.
  284. DxilEntryPropsMap m_DxilEntryPropsMap;
  285. // Keeps track of patch constant functions used by hull shaders
  286. std::unordered_set<const llvm::Function *> m_PatchConstantFunctions;
  287. // Serialized ViewId state.
  288. std::vector<unsigned> m_SerializedState;
  289. // DXIL metadata serialization/deserialization.
  290. llvm::MDTuple *EmitDxilResources();
  291. void LoadDxilResources(const llvm::MDOperand &MDO);
  292. // Helpers.
  293. template<typename T> unsigned AddResource(std::vector<std::unique_ptr<T> > &Vec, std::unique_ptr<T> pRes);
  294. void LoadDxilSignature(const llvm::MDTuple *pSigTuple, DxilSignature &Sig, bool bInput);
  295. // properties from HLModule preserved as ShaderFlags
  296. bool m_bDisableOptimizations;
  297. bool m_bUseMinPrecision;
  298. bool m_bAllResourcesBound;
  299. // properties from HLModule that should not make it to the final DXIL
  300. uint32_t m_IntermediateFlags;
  301. uint32_t m_AutoBindingSpace;
  302. std::unique_ptr<DxilSubobjects> m_pSubobjects;
  303. // m_bMetadataErrors is true if non-fatal metadata errors were encountered.
  304. // Validator will fail in this case, but should not block module load.
  305. bool m_bMetadataErrors;
  306. };
  307. } // namespace hlsl