AzslcBackend.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #pragma once
  9. #include "AzslcListener.h"
  10. #include "NewLineCounterStream.h"
  11. #include "jsoncpp/dist/json/json.h"
  12. namespace AZ::ShaderCompiler
  13. {
  14. struct PlatformEmitter;
  15. struct DescriptorCountBounds
  16. {
  17. int m_descriptorsTotal = -1; //!< negative values deactivate the check
  18. int m_spaces = -1;
  19. int m_samplers = -1;
  20. int m_textures = -1;
  21. int m_buffers = -1;
  22. };
  23. //! This structure is typically filled from parsed user settings from the command line
  24. struct Options
  25. {
  26. bool m_useUniqueIndices = false;
  27. bool m_emitConstantBufferBody = false;
  28. bool m_emitRootSig = false;
  29. bool m_forceMatrixRowMajor = false; //!< False by default (HLSL standard)
  30. bool m_forceEmitMajor = false; //!< True if either -Zpc or -Zpr was specified
  31. bool m_padRootConstantCB = false; //!< If True, the emitted root constant CB will padded to 16-byte boundary.
  32. bool m_skipAlignmentValidation = false; //! < If True, disables validation of a known DXC issue when certain word or 2-words size variables are preceded by some MatrixRxC variables.
  33. DescriptorCountBounds m_minAvailableDescriptors; //!< Hint about the targeted graphics API's minimal guaranteed usable descriptors
  34. int m_maxSpaces = std::numeric_limits<int>::max(); //!< Maximum allocatable register logical space, after which register indexes will accumulate, but spaces will be capped
  35. int m_rootConstantsMaxSize = std::numeric_limits<int>::max(); //!< Indicates the number of root constants to be allowed, 0 means root constants not enabled
  36. Packing::Layout m_packConstantBuffers = Packing::Layout::DirectXPacking; //!< Packing standard for constant buffers (uniform)
  37. Packing::Layout m_packDataBuffers = Packing::Layout::CStylePacking; //!< Packing standard for data buffer views
  38. };
  39. struct Binding
  40. {
  41. int m_registerIndex = -1;
  42. int m_logicalSpace = -1;
  43. };
  44. //! store 2 sets of binding points: one calculated purely (untainted), and one calculated with space compression (SRG-Merging)
  45. struct BindingPair
  46. {
  47. MAKE_REFLECTABLE_ENUM(Set, Untainted, Merged);
  48. std::array<Binding, Set::EndEnumeratorSentinel_> m_pair;
  49. };
  50. struct RootSigDesc
  51. {
  52. struct SrgParamDesc
  53. {
  54. IdentifierUID m_uid;
  55. RootParamType m_type;
  56. BindingPair m_registerBinding;
  57. int m_registerRange = -1;
  58. int m_num32BitConstants = -1;
  59. // This flag is added so m_registerRange can take the value
  60. // of 1 and at the same time We do not forget that m_uid refers
  61. // to an unbounded array.
  62. bool m_isUnboundedArray = false;
  63. };
  64. struct SrgDesc
  65. {
  66. IdentifierUID m_uid;
  67. vector<SrgParamDesc> m_parameters;
  68. };
  69. const SrgParamDesc& Get(const IdentifierUID& uid) const
  70. {
  71. return m_descriptorMap.at(uid);
  72. }
  73. vector<SrgDesc> m_srGroups;
  74. unordered_map<IdentifierUID, SrgParamDesc> m_descriptorMap;
  75. };
  76. //! Stateful tracker that helps to construct binding points, by counting up
  77. struct SingleBindingLocationTracker
  78. {
  79. //! Increments logical space index and nullifies all register indices
  80. void IncrementSpace();
  81. //! Equalizes all register indices (important for platforms with no B,T,S,U distinction)
  82. void UnifyIndices();
  83. //! Access total burned up resources, e.g for hardware capacity checks
  84. int GetAccumulated(BindingType r) const;
  85. int m_space = 0; //<! logical space
  86. int m_registerPos[BindingType::EndEnumeratorSentinel_] = {0}; //!< register index, one by type.
  87. int m_accumulated[BindingType::EndEnumeratorSentinel_] = {0}; //!< Counter for total usage independently from space increments
  88. int m_accumulatedUnused[BindingType::EndEnumeratorSentinel_] = {0}; //!< Counter for holes created by indices unification
  89. };
  90. //! Because of space limitations on some devices, we needed to introduce SRG-merging.
  91. //! For minimal engine impact, we need to be able to reflect the "untainted" (non-merged) binding scheme,
  92. //! and the merged scheme together. For that purpose, we will track 2 binding locations in that maker.
  93. class MultiBindingLocationMaker
  94. {
  95. public:
  96. MultiBindingLocationMaker(const Options& options)
  97. : m_options(options)
  98. {}
  99. void SignalIncrementSpace(std::function<void(int, int)> warningMessageFunctionForMinDescOvershoot);
  100. void SignalUnifyIndices();
  101. void SignalRegisterIncrement(BindingType regType, int count = 1);
  102. BindingPair GetCurrent(BindingType regType);
  103. SingleBindingLocationTracker m_untainted;
  104. SingleBindingLocationTracker m_merged;
  105. Options m_options;
  106. };
  107. //! This class intends to be a base umbrella for compiler back-end services.
  108. //! A back-end service typically provides reflection or code emission.
  109. //! Since there are re-used commonalities in such systems, it is helpful
  110. //! to share their common data and methods in this base class.
  111. class Backend
  112. {
  113. public:
  114. Backend(IntermediateRepresentation* ir, TokenStream* tokens)
  115. : m_ir(ir), m_tokens(tokens)
  116. {}
  117. //! Gets the IntermediateRepresentation object
  118. const IntermediateRepresentation* GetIR() const { return m_ir; }
  119. //! Make a string that lists all type qualifiers/modifiers in HLSL format
  120. static string GetTypeModifier(const ExtendedTypeInfo&, const Options& options, Modifiers bannedFlags = {});
  121. //! Get HLSL form of in/out modifiers
  122. static const char* GetInputModifier(const TypeQualifiers& typeQualifier);
  123. //! Fabricate a HLSL snippet that represents the type stored in typeInfo. Relevant options relate to matrix qualifiers.
  124. //! \param banned is the Flag you can setup to list a collection of type qualifiers you don't want to reproduce.
  125. string GetExtendedTypeInfo(const ExtendedTypeInfo& extTypeInfo, const Options& options, Modifiers banned, std::function<string(const TypeRefInfo&)> translator) const;
  126. protected:
  127. //! Obtains a supplement emitter which provides per-platform emission functionality.
  128. const PlatformEmitter& GetPlatformEmitter() const;
  129. //! Gets the next and increments tokenIndex. TokenIndex must be in the [misc::Interval.a, misc::Interval.b] range. Token cannot be nullptr.
  130. auto GetNextToken(ssize_t& tokenIndex, size_t channel = Token::DEFAULT_CHANNEL) const -> antlr4::Token*;
  131. virtual void EmitTranspiledTokens(misc::Interval interval, Streamable& output) const;
  132. string GetTranspiledTokens(misc::Interval interval) const;
  133. string GetInitializerClause(const AZ::ShaderCompiler::VarInfo* varInfo) const;
  134. uint32_t GetNumberOf32BitConstants(const Options& options, const IdentifierUID& uid) const;
  135. RootSigDesc BuildSignatureDescription(const Options& options, int num32BitConst) const;
  136. RootSigDesc::SrgParamDesc ReflectOneExternalResource(IdentifierUID id, MultiBindingLocationMaker& bindInfo, RootSigDesc& rootSig) const;
  137. RootSigDesc::SrgParamDesc ReflectOneExternalResourceAndWrapWithUnifyIndices(IdentifierUID id, MultiBindingLocationMaker& bindInfo, RootSigDesc& rootSig) const;
  138. void AppendOptionRange(Json::Value& varOption, const IdentifierUID& varUid, const AZ::ShaderCompiler::VarInfo* varInfo, const Options& options) const;
  139. Json::Value GetVariantList(const Options& options, bool includeEmpty = false) const;
  140. IntermediateRepresentation* m_ir;
  141. TokenStream* m_tokens;
  142. };
  143. // independent utility functions
  144. bool IsReadWriteView(string_view viewName);
  145. QualifiedName MakeSrgConstantsStructName(IdentifierUID srg);
  146. QualifiedName MakeSrgConstantsCBName(IdentifierUID srg);
  147. /// don't use for HLSL emission (this doesn't go through translation)
  148. string UnmangleTrimedName(const QualifiedNameView name);
  149. string JoinAllNestedNamesWithUnderscore(const QualifiedNameView name);
  150. string GetGlobalRootConstantVarName(const QualifiedNameView name);
  151. string GetShaderKeyFunctionName(const IdentifierUID& uid);
  152. string GetRootConstFunctionName(const IdentifierUID& uid);
  153. // don't use for HLSL emission (this doesn't go through translation)
  154. string UnmangleTrimedName(const ExtendedTypeInfo& extTypeInfo);
  155. Streamable& operator << (Streamable& out, const SamplerStateDesc::AddressMode& addressMode);
  156. Streamable& operator << (Streamable& out, const SamplerStateDesc::ComparisonFunc& compFunc);
  157. Streamable& operator << (Streamable& out, const SamplerStateDesc::BorderColor& borderColor);
  158. Streamable& operator << (Streamable& out, const SamplerStateDesc& samplerDesc);
  159. Streamable& operator << (Streamable& out, const SamplerStateDesc::ReductionType& redcType);
  160. }