1 /*
2  * Copyright 2016-2020 Robert Konrad
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef SPIRV_HLSL_HPP
18 #define SPIRV_HLSL_HPP
19 
20 #include "spirv_glsl.hpp"
21 #include <utility>
22 
23 namespace SPIRV_CROSS_NAMESPACE
24 {
25 // Interface which remaps vertex inputs to a fixed semantic name to make linking easier.
26 struct HLSLVertexAttributeRemap
27 {
28 	uint32_t location;
29 	std::string semantic;
30 };
31 // Specifying a root constant (d3d12) or push constant range (vulkan).
32 //
33 // `start` and `end` denotes the range of the root constant in bytes.
34 // Both values need to be multiple of 4.
35 struct RootConstants
36 {
37 	uint32_t start;
38 	uint32_t end;
39 
40 	uint32_t binding;
41 	uint32_t space;
42 };
43 
44 // For finer control, decorations may be removed from specific resources instead with unset_decoration().
45 enum HLSLBindingFlagBits
46 {
47 	HLSL_BINDING_AUTO_NONE_BIT = 0,
48 
49 	// Push constant (root constant) resources will be declared as CBVs (b-space) without a register() declaration.
50 	// A register will be automatically assigned by the D3D compiler, but must therefore be reflected in D3D-land.
51 	// Push constants do not normally have a DecorationBinding set, but if they do, this can be used to ignore it.
52 	HLSL_BINDING_AUTO_PUSH_CONSTANT_BIT = 1 << 0,
53 
54 	// cbuffer resources will be declared as CBVs (b-space) without a register() declaration.
55 	// A register will be automatically assigned, but must be reflected in D3D-land.
56 	HLSL_BINDING_AUTO_CBV_BIT = 1 << 1,
57 
58 	// All SRVs (t-space) will be declared without a register() declaration.
59 	HLSL_BINDING_AUTO_SRV_BIT = 1 << 2,
60 
61 	// All UAVs (u-space) will be declared without a register() declaration.
62 	HLSL_BINDING_AUTO_UAV_BIT = 1 << 3,
63 
64 	// All samplers (s-space) will be declared without a register() declaration.
65 	HLSL_BINDING_AUTO_SAMPLER_BIT = 1 << 4,
66 
67 	// No resources will be declared with register().
68 	HLSL_BINDING_AUTO_ALL = 0x7fffffff
69 };
70 using HLSLBindingFlags = uint32_t;
71 
72 // By matching stage, desc_set and binding for a SPIR-V resource,
73 // register bindings are set based on whether the HLSL resource is a
74 // CBV, UAV, SRV or Sampler. A single binding in SPIR-V might contain multiple
75 // resource types, e.g. COMBINED_IMAGE_SAMPLER, and SRV/Sampler bindings will be used respectively.
76 // On SM 5.0 and lower, register_space is ignored.
77 //
78 // To remap a push constant block which does not have any desc_set/binding associated with it,
79 // use ResourceBindingPushConstant{DescriptorSet,Binding} as values for desc_set/binding.
80 // For deeper control of push constants, set_root_constant_layouts() can be used instead.
81 struct HLSLResourceBinding
82 {
83 	spv::ExecutionModel stage = spv::ExecutionModelMax;
84 	uint32_t desc_set = 0;
85 	uint32_t binding = 0;
86 
87 	struct Binding
88 	{
89 		uint32_t register_space = 0;
90 		uint32_t register_binding = 0;
91 	} cbv, uav, srv, sampler;
92 };
93 
94 class CompilerHLSL : public CompilerGLSL
95 {
96 public:
97 	struct Options
98 	{
99 		uint32_t shader_model = 30; // TODO: map ps_4_0_level_9_0,... somehow
100 
101 		// Allows the PointSize builtin, and ignores it, as PointSize is not supported in HLSL.
102 		bool point_size_compat = false;
103 
104 		// Allows the PointCoord builtin, returns float2(0.5, 0.5), as PointCoord is not supported in HLSL.
105 		bool point_coord_compat = false;
106 
107 		// If true, the backend will assume that VertexIndex and InstanceIndex will need to apply
108 		// a base offset, and you will need to fill in a cbuffer with offsets.
109 		// Set to false if you know you will never use base instance or base vertex
110 		// functionality as it might remove an internal cbuffer.
111 		bool support_nonzero_base_vertex_base_instance = false;
112 
113 		// Forces a storage buffer to always be declared as UAV, even if the readonly decoration is used.
114 		// By default, a readonly storage buffer will be declared as ByteAddressBuffer (SRV) instead.
115 		bool force_storage_buffer_as_uav = false;
116 
117 		// Forces any storage image type marked as NonWritable to be considered an SRV instead.
118 		// For this to work with function call parameters, NonWritable must be considered to be part of the type system
119 		// so that NonWritable image arguments are also translated to Texture rather than RWTexture.
120 		bool nonwritable_uav_texture_as_srv = false;
121 	};
122 
CompilerHLSL(std::vector<uint32_t> spirv_)123 	explicit CompilerHLSL(std::vector<uint32_t> spirv_)
124 	    : CompilerGLSL(std::move(spirv_))
125 	{
126 	}
127 
CompilerHLSL(const uint32_t * ir_,size_t size)128 	CompilerHLSL(const uint32_t *ir_, size_t size)
129 	    : CompilerGLSL(ir_, size)
130 	{
131 	}
132 
CompilerHLSL(const ParsedIR & ir_)133 	explicit CompilerHLSL(const ParsedIR &ir_)
134 	    : CompilerGLSL(ir_)
135 	{
136 	}
137 
CompilerHLSL(ParsedIR && ir_)138 	explicit CompilerHLSL(ParsedIR &&ir_)
139 	    : CompilerGLSL(std::move(ir_))
140 	{
141 	}
142 
get_hlsl_options() const143 	const Options &get_hlsl_options() const
144 	{
145 		return hlsl_options;
146 	}
147 
set_hlsl_options(const Options & opts)148 	void set_hlsl_options(const Options &opts)
149 	{
150 		hlsl_options = opts;
151 	}
152 
153 	// Optionally specify a custom root constant layout.
154 	//
155 	// Push constants ranges will be split up according to the
156 	// layout specified.
157 	void set_root_constant_layouts(std::vector<RootConstants> layout);
158 
159 	// Compiles and remaps vertex attributes at specific locations to a fixed semantic.
160 	// The default is TEXCOORD# where # denotes location.
161 	// Matrices are unrolled to vectors with notation ${SEMANTIC}_#, where # denotes row.
162 	// $SEMANTIC is either TEXCOORD# or a semantic name specified here.
163 	void add_vertex_attribute_remap(const HLSLVertexAttributeRemap &vertex_attributes);
164 	std::string compile() override;
165 
166 	// This is a special HLSL workaround for the NumWorkGroups builtin.
167 	// This does not exist in HLSL, so the calling application must create a dummy cbuffer in
168 	// which the application will store this builtin.
169 	// The cbuffer layout will be:
170 	// cbuffer SPIRV_Cross_NumWorkgroups : register(b#, space#) { uint3 SPIRV_Cross_NumWorkgroups_count; };
171 	// This must be called before compile().
172 	// The function returns 0 if NumWorkGroups builtin is not statically used in the shader from the current entry point.
173 	// If non-zero, this returns the variable ID of a cbuffer which corresponds to
174 	// the cbuffer declared above. By default, no binding or descriptor set decoration is set,
175 	// so the calling application should declare explicit bindings on this ID before calling compile().
176 	VariableID remap_num_workgroups_builtin();
177 
178 	// Controls how resource bindings are declared in the output HLSL.
179 	void set_resource_binding_flags(HLSLBindingFlags flags);
180 
181 	// resource is a resource binding to indicate the HLSL CBV, SRV, UAV or sampler binding
182 	// to use for a particular SPIR-V description set
183 	// and binding. If resource bindings are provided,
184 	// is_hlsl_resource_binding_used() will return true after calling ::compile() if
185 	// the set/binding combination was used by the HLSL code.
186 	void add_hlsl_resource_binding(const HLSLResourceBinding &resource);
187 	bool is_hlsl_resource_binding_used(spv::ExecutionModel model, uint32_t set, uint32_t binding) const;
188 
189 private:
190 	std::string type_to_glsl(const SPIRType &type, uint32_t id = 0) override;
191 	std::string image_type_hlsl(const SPIRType &type, uint32_t id);
192 	std::string image_type_hlsl_modern(const SPIRType &type, uint32_t id);
193 	std::string image_type_hlsl_legacy(const SPIRType &type, uint32_t id);
194 	void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags) override;
195 	void emit_hlsl_entry_point();
196 	void emit_header() override;
197 	void emit_resources();
198 	void declare_undefined_values() override;
199 	void emit_interface_block_globally(const SPIRVariable &type);
200 	void emit_interface_block_in_struct(const SPIRVariable &type, std::unordered_set<uint32_t> &active_locations);
201 	void emit_builtin_inputs_in_struct();
202 	void emit_builtin_outputs_in_struct();
203 	void emit_texture_op(const Instruction &i) override;
204 	void emit_instruction(const Instruction &instruction) override;
205 	void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
206 	                  uint32_t count) override;
207 	void emit_buffer_block(const SPIRVariable &type) override;
208 	void emit_push_constant_block(const SPIRVariable &var) override;
209 	void emit_uniform(const SPIRVariable &var) override;
210 	void emit_modern_uniform(const SPIRVariable &var);
211 	void emit_legacy_uniform(const SPIRVariable &var);
212 	void emit_specialization_constants_and_structs();
213 	void emit_composite_constants();
214 	void emit_fixup() override;
215 	std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage) override;
216 	std::string layout_for_member(const SPIRType &type, uint32_t index) override;
217 	std::string to_interpolation_qualifiers(const Bitset &flags) override;
218 	std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type) override;
219 	std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id) override;
220 	std::string to_sampler_expression(uint32_t id);
221 	std::string to_resource_binding(const SPIRVariable &var);
222 	std::string to_resource_binding_sampler(const SPIRVariable &var);
223 	std::string to_resource_register(HLSLBindingFlagBits flag, char space, uint32_t binding, uint32_t set);
224 	void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id) override;
225 	void emit_access_chain(const Instruction &instruction);
226 	void emit_load(const Instruction &instruction);
227 	void read_access_chain(std::string *expr, const std::string &lhs, const SPIRAccessChain &chain);
228 	void read_access_chain_struct(const std::string &lhs, const SPIRAccessChain &chain);
229 	void read_access_chain_array(const std::string &lhs, const SPIRAccessChain &chain);
230 	void write_access_chain(const SPIRAccessChain &chain, uint32_t value, const SmallVector<uint32_t> &composite_chain);
231 	void write_access_chain_struct(const SPIRAccessChain &chain, uint32_t value,
232 	                               const SmallVector<uint32_t> &composite_chain);
233 	void write_access_chain_array(const SPIRAccessChain &chain, uint32_t value,
234 	                              const SmallVector<uint32_t> &composite_chain);
235 	std::string write_access_chain_value(uint32_t value, const SmallVector<uint32_t> &composite_chain, bool enclose);
236 	void emit_store(const Instruction &instruction);
237 	void emit_atomic(const uint32_t *ops, uint32_t length, spv::Op op);
238 	void emit_subgroup_op(const Instruction &i) override;
239 	void emit_block_hints(const SPIRBlock &block) override;
240 
241 	void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index, const std::string &qualifier,
242 	                        uint32_t base_offset = 0) override;
243 
244 	const char *to_storage_qualifiers_glsl(const SPIRVariable &var) override;
245 	void replace_illegal_names() override;
246 
247 	Options hlsl_options;
248 
249 	// TODO: Refactor this to be more similar to MSL, maybe have some common system in place?
250 	bool requires_op_fmod = false;
251 	bool requires_fp16_packing = false;
252 	bool requires_explicit_fp16_packing = false;
253 	bool requires_unorm8_packing = false;
254 	bool requires_snorm8_packing = false;
255 	bool requires_unorm16_packing = false;
256 	bool requires_snorm16_packing = false;
257 	bool requires_bitfield_insert = false;
258 	bool requires_bitfield_extract = false;
259 	bool requires_inverse_2x2 = false;
260 	bool requires_inverse_3x3 = false;
261 	bool requires_inverse_4x4 = false;
262 	bool requires_scalar_reflect = false;
263 	bool requires_scalar_refract = false;
264 	bool requires_scalar_faceforward = false;
265 	uint64_t required_textureSizeVariants = 0;
266 	void require_texture_query_variant(const SPIRType &type);
267 
268 	enum TextureQueryVariantDim
269 	{
270 		Query1D = 0,
271 		Query1DArray,
272 		Query2D,
273 		Query2DArray,
274 		Query3D,
275 		QueryBuffer,
276 		QueryCube,
277 		QueryCubeArray,
278 		Query2DMS,
279 		Query2DMSArray,
280 		QueryDimCount
281 	};
282 
283 	enum TextureQueryVariantType
284 	{
285 		QueryTypeFloat = 0,
286 		QueryTypeInt = 16,
287 		QueryTypeUInt = 32,
288 		QueryTypeCount = 3
289 	};
290 
291 	void emit_builtin_variables();
292 	bool require_output = false;
293 	bool require_input = false;
294 	SmallVector<HLSLVertexAttributeRemap> remap_vertex_attributes;
295 
296 	uint32_t type_to_consumed_locations(const SPIRType &type) const;
297 
298 	void emit_io_block(const SPIRVariable &var);
299 	std::string to_semantic(uint32_t location, spv::ExecutionModel em, spv::StorageClass sc);
300 
301 	uint32_t num_workgroups_builtin = 0;
302 	HLSLBindingFlags resource_binding_flags = 0;
303 
304 	// Custom root constant layout, which should be emitted
305 	// when translating push constant ranges.
306 	std::vector<RootConstants> root_constants_layout;
307 
308 	void validate_shader_model();
309 
310 	std::string get_unique_identifier();
311 	uint32_t unique_identifier_count = 0;
312 
313 	std::unordered_map<StageSetBinding, std::pair<HLSLResourceBinding, bool>, InternalHasher> resource_bindings;
314 	void remap_hlsl_resource_binding(HLSLBindingFlagBits type, uint32_t &desc_set, uint32_t &binding);
315 };
316 } // namespace SPIRV_CROSS_NAMESPACE
317 
318 #endif
319