Debian Codegraph @

third_party/spirv-cross/spirv_msl.hpp

raw
1 /*
2 * Copyright 2016-2020 The Brenwill Workshop Ltd.
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_CROSS_MSL_HPP
18 #define SPIRV_CROSS_MSL_HPP
19
20 #include "spirv_glsl.hpp"
21 #include <map>
22 #include <set>
23 #include <stddef.h>
24 #include <unordered_map>
25 #include <unordered_set>
26
27 namespace SPIRV_CROSS_NAMESPACE
28 {
29
30 // Indicates the format of a shader input. Currently limited to specifying
31 // if the input is an 8-bit unsigned integer, 16-bit unsigned integer, or
32 // some other format.
33 enum MSLShaderInputFormat
34 {
35 MSL_SHADER_INPUT_FORMAT_OTHER = 0,
36 MSL_SHADER_INPUT_FORMAT_UINT8 = 1,
37 MSL_SHADER_INPUT_FORMAT_UINT16 = 2,
38 MSL_SHADER_INPUT_FORMAT_ANY16 = 3,
39 MSL_SHADER_INPUT_FORMAT_ANY32 = 4,
40
41 // Deprecated aliases.
42 MSL_VERTEX_FORMAT_OTHER = MSL_SHADER_INPUT_FORMAT_OTHER,
43 MSL_VERTEX_FORMAT_UINT8 = MSL_SHADER_INPUT_FORMAT_UINT8,
44 MSL_VERTEX_FORMAT_UINT16 = MSL_SHADER_INPUT_FORMAT_UINT16,
45
46 MSL_SHADER_INPUT_FORMAT_INT_MAX = 0x7fffffff
47 };
48
49 // Defines MSL characteristics of an input variable at a particular location.
50 // After compilation, it is possible to query whether or not this location was used.
51 // If vecsize is nonzero, it must be greater than or equal to the vecsize declared in the shader,
52 // or behavior is undefined.
53 struct MSLShaderInput
54 {
55 uint32_t location = 0;
56 MSLShaderInputFormat format = MSL_SHADER_INPUT_FORMAT_OTHER;
57 spv::BuiltIn builtin = spv::BuiltInMax;
58 uint32_t vecsize = 0;
59 };
60
61 // Matches the binding index of a MSL resource for a binding within a descriptor set.
62 // Taken together, the stage, desc_set and binding combine to form a reference to a resource
63 // descriptor used in a particular shading stage. The count field indicates the number of
64 // resources consumed by this binding, if the binding represents an array of resources.
65 // If the resource array is a run-time-sized array, which are legal in GLSL or SPIR-V, this value
66 // will be used to declare the array size in MSL, which does not support run-time-sized arrays.
67 // For resources that are not held in a run-time-sized array, the count field does not need to be populated.
68 // If using MSL 2.0 argument buffers, the descriptor set is not marked as a discrete descriptor set,
69 // and (for iOS only) the resource is not a storage image (sampled != 2), the binding reference we
70 // remap to will become an [[id(N)]] attribute within the "descriptor set" argument buffer structure.
71 // For resources which are bound in the "classic" MSL 1.0 way or discrete descriptors, the remap will become a
72 // [[buffer(N)]], [[texture(N)]] or [[sampler(N)]] depending on the resource types used.
73 struct MSLResourceBinding
74 {
75 spv::ExecutionModel stage = spv::ExecutionModelMax;
76 uint32_t desc_set = 0;
77 uint32_t binding = 0;
78 uint32_t count = 0;
79 uint32_t msl_buffer = 0;
80 uint32_t msl_texture = 0;
81 uint32_t msl_sampler = 0;
82 };
83
84 enum MSLSamplerCoord
85 {
86 MSL_SAMPLER_COORD_NORMALIZED = 0,
87 MSL_SAMPLER_COORD_PIXEL = 1,
88 MSL_SAMPLER_INT_MAX = 0x7fffffff
89 };
90
91 enum MSLSamplerFilter
92 {
93 MSL_SAMPLER_FILTER_NEAREST = 0,
94 MSL_SAMPLER_FILTER_LINEAR = 1,
95 MSL_SAMPLER_FILTER_INT_MAX = 0x7fffffff
96 };
97
98 enum MSLSamplerMipFilter
99 {
100 MSL_SAMPLER_MIP_FILTER_NONE = 0,
101 MSL_SAMPLER_MIP_FILTER_NEAREST = 1,
102 MSL_SAMPLER_MIP_FILTER_LINEAR = 2,
103 MSL_SAMPLER_MIP_FILTER_INT_MAX = 0x7fffffff
104 };
105
106 enum MSLSamplerAddress
107 {
108 MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO = 0,
109 MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE = 1,
110 MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER = 2,
111 MSL_SAMPLER_ADDRESS_REPEAT = 3,
112 MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT = 4,
113 MSL_SAMPLER_ADDRESS_INT_MAX = 0x7fffffff
114 };
115
116 enum MSLSamplerCompareFunc
117 {
118 MSL_SAMPLER_COMPARE_FUNC_NEVER = 0,
119 MSL_SAMPLER_COMPARE_FUNC_LESS = 1,
120 MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL = 2,
121 MSL_SAMPLER_COMPARE_FUNC_GREATER = 3,
122 MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL = 4,
123 MSL_SAMPLER_COMPARE_FUNC_EQUAL = 5,
124 MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL = 6,
125 MSL_SAMPLER_COMPARE_FUNC_ALWAYS = 7,
126 MSL_SAMPLER_COMPARE_FUNC_INT_MAX = 0x7fffffff
127 };
128
129 enum MSLSamplerBorderColor
130 {
131 MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK = 0,
132 MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK = 1,
133 MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE = 2,
134 MSL_SAMPLER_BORDER_COLOR_INT_MAX = 0x7fffffff
135 };
136
137 enum MSLFormatResolution
138 {
139 MSL_FORMAT_RESOLUTION_444 = 0,
140 MSL_FORMAT_RESOLUTION_422,
141 MSL_FORMAT_RESOLUTION_420,
142 MSL_FORMAT_RESOLUTION_INT_MAX = 0x7fffffff
143 };
144
145 enum MSLChromaLocation
146 {
147 MSL_CHROMA_LOCATION_COSITED_EVEN = 0,
148 MSL_CHROMA_LOCATION_MIDPOINT,
149 MSL_CHROMA_LOCATION_INT_MAX = 0x7fffffff
150 };
151
152 enum MSLComponentSwizzle
153 {
154 MSL_COMPONENT_SWIZZLE_IDENTITY = 0,
155 MSL_COMPONENT_SWIZZLE_ZERO,
156 MSL_COMPONENT_SWIZZLE_ONE,
157 MSL_COMPONENT_SWIZZLE_R,
158 MSL_COMPONENT_SWIZZLE_G,
159 MSL_COMPONENT_SWIZZLE_B,
160 MSL_COMPONENT_SWIZZLE_A,
161 MSL_COMPONENT_SWIZZLE_INT_MAX = 0x7fffffff
162 };
163
164 enum MSLSamplerYCbCrModelConversion
165 {
166 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY = 0,
167 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY,
168 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709,
169 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601,
170 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020,
171 MSL_SAMPLER_YCBCR_MODEL_CONVERSION_INT_MAX = 0x7fffffff
172 };
173
174 enum MSLSamplerYCbCrRange
175 {
176 MSL_SAMPLER_YCBCR_RANGE_ITU_FULL = 0,
177 MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW,
178 MSL_SAMPLER_YCBCR_RANGE_INT_MAX = 0x7fffffff
179 };
180
181 struct MSLConstexprSampler
182 {
183 MSLSamplerCoord coord = MSL_SAMPLER_COORD_NORMALIZED;
184 MSLSamplerFilter min_filter = MSL_SAMPLER_FILTER_NEAREST;
185 MSLSamplerFilter mag_filter = MSL_SAMPLER_FILTER_NEAREST;
186 MSLSamplerMipFilter mip_filter = MSL_SAMPLER_MIP_FILTER_NONE;
187 MSLSamplerAddress s_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
188 MSLSamplerAddress t_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
189 MSLSamplerAddress r_address = MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE;
190 MSLSamplerCompareFunc compare_func = MSL_SAMPLER_COMPARE_FUNC_NEVER;
191 MSLSamplerBorderColor border_color = MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK;
192 float lod_clamp_min = 0.0f;
193 float lod_clamp_max = 1000.0f;
194 int max_anisotropy = 1;
195
196 // Sampler Y'CbCr conversion parameters
197 uint32_t planes = 0;
198 MSLFormatResolution resolution = MSL_FORMAT_RESOLUTION_444;
199 MSLSamplerFilter chroma_filter = MSL_SAMPLER_FILTER_NEAREST;
200 MSLChromaLocation x_chroma_offset = MSL_CHROMA_LOCATION_COSITED_EVEN;
201 MSLChromaLocation y_chroma_offset = MSL_CHROMA_LOCATION_COSITED_EVEN;
202 MSLComponentSwizzle swizzle[4]; // IDENTITY, IDENTITY, IDENTITY, IDENTITY
203 MSLSamplerYCbCrModelConversion ycbcr_model = MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY;
204 MSLSamplerYCbCrRange ycbcr_range = MSL_SAMPLER_YCBCR_RANGE_ITU_FULL;
205 uint32_t bpc = 8;
206
207 bool compare_enable = false;
208 bool lod_clamp_enable = false;
209 bool anisotropy_enable = false;
210 bool ycbcr_conversion_enable = false;
211
212 MSLConstexprSampler()
213 {
214 for (uint32_t i = 0; i < 4; i++)
215 swizzle[i] = MSL_COMPONENT_SWIZZLE_IDENTITY;
216 }
217 bool swizzle_is_identity() const
218 {
219 return (swizzle[0] == MSL_COMPONENT_SWIZZLE_IDENTITY && swizzle[1] == MSL_COMPONENT_SWIZZLE_IDENTITY &&
220 swizzle[2] == MSL_COMPONENT_SWIZZLE_IDENTITY && swizzle[3] == MSL_COMPONENT_SWIZZLE_IDENTITY);
221 }
222 bool swizzle_has_one_or_zero() const
223 {
224 return (swizzle[0] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[0] == MSL_COMPONENT_SWIZZLE_ONE ||
225 swizzle[1] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[1] == MSL_COMPONENT_SWIZZLE_ONE ||
226 swizzle[2] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[2] == MSL_COMPONENT_SWIZZLE_ONE ||
227 swizzle[3] == MSL_COMPONENT_SWIZZLE_ZERO || swizzle[3] == MSL_COMPONENT_SWIZZLE_ONE);
228 }
229 };
230
231 // Special constant used in a MSLResourceBinding desc_set
232 // element to indicate the bindings for the push constants.
233 // Kinda deprecated. Just use ResourceBindingPushConstant{DescriptorSet,Binding} directly.
234 static const uint32_t kPushConstDescSet = ResourceBindingPushConstantDescriptorSet;
235
236 // Special constant used in a MSLResourceBinding binding
237 // element to indicate the bindings for the push constants.
238 // Kinda deprecated. Just use ResourceBindingPushConstant{DescriptorSet,Binding} directly.
239 static const uint32_t kPushConstBinding = ResourceBindingPushConstantBinding;
240
241 // Special constant used in a MSLResourceBinding binding
242 // element to indicate the buffer binding for swizzle buffers.
243 static const uint32_t kSwizzleBufferBinding = ~(1u);
244
245 // Special constant used in a MSLResourceBinding binding
246 // element to indicate the buffer binding for buffer size buffers to support OpArrayLength.
247 static const uint32_t kBufferSizeBufferBinding = ~(2u);
248
249 // Special constant used in a MSLResourceBinding binding
250 // element to indicate the buffer binding used for the argument buffer itself.
251 // This buffer binding should be kept as small as possible as all automatic bindings for buffers
252 // will start at max(kArgumentBufferBinding) + 1.
253 static const uint32_t kArgumentBufferBinding = ~(3u);
254
255 static const uint32_t kMaxArgumentBuffers = 8;
256
257 // The arbitrary maximum for the nesting of array of array copies.
258 static const uint32_t kArrayCopyMultidimMax = 6;
259
260 // Decompiles SPIR-V to Metal Shading Language
261 class CompilerMSL : public CompilerGLSL
262 {
263 public:
264 // Options for compiling to Metal Shading Language
265 struct Options
266 {
267 typedef enum
268 {
269 iOS = 0,
270 macOS = 1
271 } Platform;
272
273 Platform platform = macOS;
274 uint32_t msl_version = make_msl_version(1, 2);
275 uint32_t texel_buffer_texture_width = 4096; // Width of 2D Metal textures used as 1D texel buffers
276 uint32_t r32ui_linear_texture_alignment = 4;
277 uint32_t r32ui_alignment_constant_id = 65535;
278 uint32_t swizzle_buffer_index = 30;
279 uint32_t indirect_params_buffer_index = 29;
280 uint32_t shader_output_buffer_index = 28;
281 uint32_t shader_patch_output_buffer_index = 27;
282 uint32_t shader_tess_factor_buffer_index = 26;
283 uint32_t buffer_size_buffer_index = 25;
284 uint32_t view_mask_buffer_index = 24;
285 uint32_t dynamic_offsets_buffer_index = 23;
286 uint32_t shader_input_buffer_index = 22;
287 uint32_t shader_index_buffer_index = 21;
288 uint32_t shader_input_wg_index = 0;
289 uint32_t device_index = 0;
290 uint32_t enable_frag_output_mask = 0xffffffff;
291 // Metal doesn't allow setting a fixed sample mask directly in the pipeline.
292 // We can evade this restriction by ANDing the internal sample_mask output
293 // of the shader with the additional fixed sample mask.
294 uint32_t additional_fixed_sample_mask = 0xffffffff;
295 bool enable_point_size_builtin = true;
296 bool enable_frag_depth_builtin = true;
297 bool enable_frag_stencil_ref_builtin = true;
298 bool disable_rasterization = false;
299 bool capture_output_to_buffer = false;
300 bool swizzle_texture_samples = false;
301 bool tess_domain_origin_lower_left = false;
302 bool multiview = false;
303 bool multiview_layered_rendering = true;
304 bool view_index_from_device_index = false;
305 bool dispatch_base = false;
306 bool texture_1D_as_2D = false;
307
308 // Enable use of MSL 2.0 indirect argument buffers.
309 // MSL 2.0 must also be enabled.
310 bool argument_buffers = false;
311
312 // Ensures vertex and instance indices start at zero. This reflects the behavior of HLSL with SV_VertexID and SV_InstanceID.
313 bool enable_base_index_zero = false;
314
315 // Fragment output in MSL must have at least as many components as the render pass.
316 // Add support to explicit pad out components.
317 bool pad_fragment_output_components = false;
318
319 // Specifies whether the iOS target version supports the [[base_vertex]] and [[base_instance]] attributes.
320 bool ios_support_base_vertex_instance = false;
321
322 // Use Metal's native frame-buffer fetch API for subpass inputs.
323 bool use_framebuffer_fetch_subpasses = false;
324
325 // Enables use of "fma" intrinsic for invariant float math
326 bool invariant_float_math = false;
327
328 // Emulate texturecube_array with texture2d_array for iOS where this type is not available
329 bool emulate_cube_array = false;
330
331 // Allow user to enable decoration binding
332 bool enable_decoration_binding = false;
333
334 // Requires MSL 2.1, use the native support for texel buffers.
335 bool texture_buffer_native = false;
336
337 // Forces all resources which are part of an argument buffer to be considered active.
338 // This ensures ABI compatibility between shaders where some resources might be unused,
339 // and would otherwise declare a different IAB.
340 bool force_active_argument_buffer_resources = false;
341
342 // Forces the use of plain arrays, which works around certain driver bugs on certain versions
343 // of Intel Macbooks. See https://github.com/KhronosGroup/SPIRV-Cross/issues/1210.
344 // May reduce performance in scenarios where arrays are copied around as value-types.
345 bool force_native_arrays = false;
346
347 // If a shader writes clip distance, also emit user varyings which
348 // can be read in subsequent stages.
349 bool enable_clip_distance_user_varying = true;
350
351 // In a tessellation control shader, assume that more than one patch can be processed in a
352 // single workgroup. This requires changes to the way the InvocationId and PrimitiveId
353 // builtins are processed, but should result in more efficient usage of the GPU.
354 bool multi_patch_workgroup = false;
355
356 // If set, a vertex shader will be compiled as part of a tessellation pipeline.
357 // It will be translated as a compute kernel, so it can use the global invocation ID
358 // to index the output buffer.
359 bool vertex_for_tessellation = false;
360
361 // Assume that SubpassData images have multiple layers. Layered input attachments
362 // are addressed relative to the Layer output from the vertex pipeline. This option
363 // has no effect with multiview, since all input attachments are assumed to be layered
364 // and will be addressed using the current ViewIndex.
365 bool arrayed_subpass_input = false;
366
367 enum class IndexType
368 {
369 None = 0,
370 UInt16 = 1,
371 UInt32 = 2
372 };
373
374 // The type of index in the index buffer, if present. For a compute shader, Metal
375 // requires specifying the indexing at pipeline creation, rather than at draw time
376 // as with graphics pipelines. This means we must create three different pipelines,
377 // for no indexing, 16-bit indices, and 32-bit indices. Each requires different
378 // handling for the gl_VertexIndex builtin. We may as well, then, create three
379 // different shaders for these three scenarios.
380 IndexType vertex_index_type = IndexType::None;
381
382 bool is_ios() const
383 {
384 return platform == iOS;
385 }
386
387 bool is_macos() const
388 {
389 return platform == macOS;
390 }
391
392 void set_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0)
393 {
394 msl_version = make_msl_version(major, minor, patch);
395 }
396
397 bool supports_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0) const
398 {
399 return msl_version >= make_msl_version(major, minor, patch);
400 }
401
402 static uint32_t make_msl_version(uint32_t major, uint32_t minor = 0, uint32_t patch = 0)
403 {
404 return (major * 10000) + (minor * 100) + patch;
405 }
406 };
407
408 const Options &get_msl_options() const
409 {
410 return msl_options;
411 }
412
413 void set_msl_options(const Options &opts)
414 {
415 msl_options = opts;
416 }
417
418 // Provide feedback to calling API to allow runtime to disable pipeline
419 // rasterization if vertex shader requires rasterization to be disabled.
420 bool get_is_rasterization_disabled() const
421 {
422 return is_rasterization_disabled && (get_entry_point().model == spv::ExecutionModelVertex ||
423 get_entry_point().model == spv::ExecutionModelTessellationControl ||
424 get_entry_point().model == spv::ExecutionModelTessellationEvaluation);
425 }
426
427 // Provide feedback to calling API to allow it to pass an auxiliary
428 // swizzle buffer if the shader needs it.
429 bool needs_swizzle_buffer() const
430 {
431 return used_swizzle_buffer;
432 }
433
434 // Provide feedback to calling API to allow it to pass a buffer
435 // containing STORAGE_BUFFER buffer sizes to support OpArrayLength.
436 bool needs_buffer_size_buffer() const
437 {
438 return !buffers_requiring_array_length.empty();
439 }
440
441 // Provide feedback to calling API to allow it to pass a buffer
442 // containing the view mask for the current multiview subpass.
443 bool needs_view_mask_buffer() const
444 {
445 return msl_options.multiview && !msl_options.view_index_from_device_index;
446 }
447
448 // Provide feedback to calling API to allow it to pass a buffer
449 // containing the dispatch base workgroup ID.
450 bool needs_dispatch_base_buffer() const
451 {
452 return msl_options.dispatch_base && !msl_options.supports_msl_version(1, 2);
453 }
454
455 // Provide feedback to calling API to allow it to pass an output
456 // buffer if the shader needs it.
457 bool needs_output_buffer() const
458 {
459 return capture_output_to_buffer && stage_out_var_id != ID(0);
460 }
461
462 // Provide feedback to calling API to allow it to pass a patch output
463 // buffer if the shader needs it.
464 bool needs_patch_output_buffer() const
465 {
466 return capture_output_to_buffer && patch_stage_out_var_id != ID(0);
467 }
468
469 // Provide feedback to calling API to allow it to pass an input threadgroup
470 // buffer if the shader needs it.
471 bool needs_input_threadgroup_mem() const
472 {
473 return capture_output_to_buffer && stage_in_var_id != ID(0);
474 }
475
476 explicit CompilerMSL(std::vector<uint32_t> spirv);
477 CompilerMSL(const uint32_t *ir, size_t word_count);
478 explicit CompilerMSL(const ParsedIR &ir);
479 explicit CompilerMSL(ParsedIR &&ir);
480
481 // input is a shader input description used to fix up shader input variables.
482 // If shader inputs are provided, is_msl_shader_input_used() will return true after
483 // calling ::compile() if the location was used by the MSL code.
484 void add_msl_shader_input(const MSLShaderInput &input);
485
486 // resource is a resource binding to indicate the MSL buffer,
487 // texture or sampler index to use for a particular SPIR-V description set
488 // and binding. If resource bindings are provided,
489 // is_msl_resource_binding_used() will return true after calling ::compile() if
490 // the set/binding combination was used by the MSL code.
491 void add_msl_resource_binding(const MSLResourceBinding &resource);
492
493 // desc_set and binding are the SPIR-V descriptor set and binding of a buffer resource
494 // in this shader. index is the index within the dynamic offset buffer to use. This
495 // function marks that resource as using a dynamic offset (VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC
496 // or VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC). This function only has any effect if argument buffers
497 // are enabled. If so, the buffer will have its address adjusted at the beginning of the shader with
498 // an offset taken from the dynamic offset buffer.
499 void add_dynamic_buffer(uint32_t desc_set, uint32_t binding, uint32_t index);
500
501 // desc_set and binding are the SPIR-V descriptor set and binding of a buffer resource
502 // in this shader. This function marks that resource as an inline uniform block
503 // (VK_DESCRIPTOR_TYPE_INLINE_UNIFORM_BLOCK_EXT). This function only has any effect if argument buffers
504 // are enabled. If so, the buffer block will be directly embedded into the argument
505 // buffer, instead of being referenced indirectly via pointer.
506 void add_inline_uniform_block(uint32_t desc_set, uint32_t binding);
507
508 // When using MSL argument buffers, we can force "classic" MSL 1.0 binding schemes for certain descriptor sets.
509 // This corresponds to VK_KHR_push_descriptor in Vulkan.
510 void add_discrete_descriptor_set(uint32_t desc_set);
511
512 // If an argument buffer is large enough, it may need to be in the device storage space rather than
513 // constant. Opt-in to this behavior here on a per set basis.
514 void set_argument_buffer_device_address_space(uint32_t desc_set, bool device_storage);
515
516 // Query after compilation is done. This allows you to check if an input location was used by the shader.
517 bool is_msl_shader_input_used(uint32_t location);
518
519 // NOTE: Only resources which are remapped using add_msl_resource_binding will be reported here.
520 // Constexpr samplers are always assumed to be emitted.
521 // No specific MSLResourceBinding remapping is required for constexpr samplers as long as they are remapped
522 // by remap_constexpr_sampler(_by_binding).
523 bool is_msl_resource_binding_used(spv::ExecutionModel model, uint32_t set, uint32_t binding) const;
524
525 // This must only be called after a successful call to CompilerMSL::compile().
526 // For a variable resource ID obtained through reflection API, report the automatically assigned resource index.
527 // If the descriptor set was part of an argument buffer, report the [[id(N)]],
528 // or [[buffer/texture/sampler]] binding for other resources.
529 // If the resource was a combined image sampler, report the image binding here,
530 // use the _secondary version of this call to query the sampler half of the resource.
531 // If no binding exists, uint32_t(-1) is returned.
532 uint32_t get_automatic_msl_resource_binding(uint32_t id) const;
533
534 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers, in which case the
535 // sampler's binding is returned instead. For any other resource type, -1 is returned.
536 uint32_t get_automatic_msl_resource_binding_secondary(uint32_t id) const;
537
538 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers for multiplanar images,
539 // in which case the second plane's binding is returned instead. For any other resource type, -1 is returned.
540 uint32_t get_automatic_msl_resource_binding_tertiary(uint32_t id) const;
541
542 // Same as get_automatic_msl_resource_binding, but should only be used for combined image samplers for triplanar images,
543 // in which case the third plane's binding is returned instead. For any other resource type, -1 is returned.
544 uint32_t get_automatic_msl_resource_binding_quaternary(uint32_t id) const;
545
546 // Compiles the SPIR-V code into Metal Shading Language.
547 std::string compile() override;
548
549 // Remap a sampler with ID to a constexpr sampler.
550 // Older iOS targets must use constexpr samplers in certain cases (PCF),
551 // so a static sampler must be used.
552 // The sampler will not consume a binding, but be declared in the entry point as a constexpr sampler.
553 // This can be used on both combined image/samplers (sampler2D) or standalone samplers.
554 // The remapped sampler must not be an array of samplers.
555 // Prefer remap_constexpr_sampler_by_binding unless you're also doing reflection anyways.
556 void remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler);
557
558 // Same as remap_constexpr_sampler, except you provide set/binding, rather than variable ID.
559 // Remaps based on ID take priority over set/binding remaps.
560 void remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding, const MSLConstexprSampler &sampler);
561
562 // If using CompilerMSL::Options::pad_fragment_output_components, override the number of components we expect
563 // to use for a particular location. The default is 4 if number of components is not overridden.
564 void set_fragment_output_components(uint32_t location, uint32_t components);
565
566 void set_combined_sampler_suffix(const char *suffix);
567 const char *get_combined_sampler_suffix() const;
568
569 protected:
570 // An enum of SPIR-V functions that are implemented in additional
571 // source code that is added to the shader if necessary.
572 enum SPVFuncImpl
573 {
574 SPVFuncImplNone,
575 SPVFuncImplMod,
576 SPVFuncImplRadians,
577 SPVFuncImplDegrees,
578 SPVFuncImplFindILsb,
579 SPVFuncImplFindSMsb,
580 SPVFuncImplFindUMsb,
581 SPVFuncImplSSign,
582 SPVFuncImplArrayCopyMultidimBase,
583 // Unfortunately, we cannot use recursive templates in the MSL compiler properly,
584 // so stamp out variants up to some arbitrary maximum.
585 SPVFuncImplArrayCopy = SPVFuncImplArrayCopyMultidimBase + 1,
586 SPVFuncImplArrayOfArrayCopy2Dim = SPVFuncImplArrayCopyMultidimBase + 2,
587 SPVFuncImplArrayOfArrayCopy3Dim = SPVFuncImplArrayCopyMultidimBase + 3,
588 SPVFuncImplArrayOfArrayCopy4Dim = SPVFuncImplArrayCopyMultidimBase + 4,
589 SPVFuncImplArrayOfArrayCopy5Dim = SPVFuncImplArrayCopyMultidimBase + 5,
590 SPVFuncImplArrayOfArrayCopy6Dim = SPVFuncImplArrayCopyMultidimBase + 6,
591 SPVFuncImplTexelBufferCoords,
592 SPVFuncImplImage2DAtomicCoords, // Emulate texture2D atomic operations
593 SPVFuncImplFMul,
594 SPVFuncImplFAdd,
595 SPVFuncImplCubemapTo2DArrayFace,
596 SPVFuncImplUnsafeArray, // Allow Metal to use the array<T> template to make arrays a value type
597 SPVFuncImplInverse4x4,
598 SPVFuncImplInverse3x3,
599 SPVFuncImplInverse2x2,
600 // It is very important that this come before *Swizzle and ChromaReconstruct*, to ensure it's
601 // emitted before them.
602 SPVFuncImplForwardArgs,
603 // Likewise, this must come before *Swizzle.
604 SPVFuncImplGetSwizzle,
605 SPVFuncImplTextureSwizzle,
606 SPVFuncImplGatherSwizzle,
607 SPVFuncImplGatherCompareSwizzle,
608 SPVFuncImplSubgroupBroadcast,
609 SPVFuncImplSubgroupBroadcastFirst,
610 SPVFuncImplSubgroupBallot,
611 SPVFuncImplSubgroupBallotBitExtract,
612 SPVFuncImplSubgroupBallotFindLSB,
613 SPVFuncImplSubgroupBallotFindMSB,
614 SPVFuncImplSubgroupBallotBitCount,
615 SPVFuncImplSubgroupAllEqual,
616 SPVFuncImplSubgroupShuffle,
617 SPVFuncImplSubgroupShuffleXor,
618 SPVFuncImplSubgroupShuffleUp,
619 SPVFuncImplSubgroupShuffleDown,
620 SPVFuncImplQuadBroadcast,
621 SPVFuncImplQuadSwap,
622 SPVFuncImplReflectScalar,
623 SPVFuncImplRefractScalar,
624 SPVFuncImplFaceForwardScalar,
625 SPVFuncImplChromaReconstructNearest2Plane,
626 SPVFuncImplChromaReconstructNearest3Plane,
627 SPVFuncImplChromaReconstructLinear422CositedEven2Plane,
628 SPVFuncImplChromaReconstructLinear422CositedEven3Plane,
629 SPVFuncImplChromaReconstructLinear422Midpoint2Plane,
630 SPVFuncImplChromaReconstructLinear422Midpoint3Plane,
631 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane,
632 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane,
633 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane,
634 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane,
635 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane,
636 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane,
637 SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane,
638 SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane,
639 SPVFuncImplExpandITUFullRange,
640 SPVFuncImplExpandITUNarrowRange,
641 SPVFuncImplConvertYCbCrBT709,
642 SPVFuncImplConvertYCbCrBT601,
643 SPVFuncImplConvertYCbCrBT2020,
644 SPVFuncImplDynamicImageSampler,
645 };
646
647 // If the underlying resource has been used for comparison then duplicate loads of that resource must be too
648 // Use Metal's native frame-buffer fetch API for subpass inputs.
649 void emit_texture_op(const Instruction &i, bool sparse) override;
650 void emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1, const char *op);
651 void emit_instruction(const Instruction &instr) override;
652 void emit_glsl_op(uint32_t result_type, uint32_t result_id, uint32_t op, const uint32_t *args,
653 uint32_t count) override;
654 void emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t result_id, uint32_t op,
655 const uint32_t *args, uint32_t count) override;
656 void emit_header() override;
657 void emit_function_prototype(SPIRFunction &func, const Bitset &return_flags) override;
658 void emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id) override;
659 void emit_subgroup_op(const Instruction &i) override;
660 std::string to_texture_op(const Instruction &i, bool sparse, bool *forward,
661 SmallVector<uint32_t> &inherited_expressions) override;
662 void emit_fixup() override;
663 std::string to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
664 const std::string &qualifier = "");
665 void emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
666 const std::string &qualifier = "", uint32_t base_offset = 0) override;
667 void emit_struct_padding_target(const SPIRType &type) override;
668 std::string type_to_glsl(const SPIRType &type, uint32_t id = 0) override;
669
670 // Allow Metal to use the array<T> template to make arrays a value type
671 std::string type_to_array_glsl(const SPIRType &type) override;
672
673 // Threadgroup arrays can't have a wrapper type
674 std::string variable_decl(const SPIRVariable &variable) override;
675
676 // GCC workaround of lambdas calling protected functions (for older GCC versions)
677 std::string variable_decl(const SPIRType &type, const std::string &name, uint32_t id = 0) override;
678
679 std::string image_type_glsl(const SPIRType &type, uint32_t id = 0) override;
680 std::string sampler_type(const SPIRType &type, uint32_t id);
681 std::string builtin_to_glsl(spv::BuiltIn builtin, spv::StorageClass storage) override;
682 std::string to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id) override;
683 std::string to_name(uint32_t id, bool allow_alias = true) const override;
684 std::string to_function_name(const TextureFunctionNameArguments &args) override;
685 std::string to_function_args(const TextureFunctionArguments &args, bool *p_forward) override;
686 std::string to_initializer_expression(const SPIRVariable &var) override;
687 std::string to_zero_initialized_expression(uint32_t type_id) override;
688
689 std::string unpack_expression_type(std::string expr_str, const SPIRType &type, uint32_t physical_type_id,
690 bool is_packed, bool row_major) override;
691
692 // Returns true for BuiltInSampleMask because gl_SampleMask[] is an array in SPIR-V, but [[sample_mask]] is a scalar in Metal.
693 bool builtin_translates_to_nonarray(spv::BuiltIn builtin) const override;
694
695 std::string bitcast_glsl_op(const SPIRType &result_type, const SPIRType &argument_type) override;
696 bool emit_complex_bitcast(uint32_t result_id, uint32_t id, uint32_t op0) override;
697 bool skip_argument(uint32_t id) const override;
698 std::string to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain) override;
699 std::string to_qualifiers_glsl(uint32_t id) override;
700 void replace_illegal_names() override;
701 void declare_undefined_values() override;
702 void declare_constant_arrays();
703
704 // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
705 void declare_complex_constant_arrays();
706
707 bool is_patch_block(const SPIRType &type);
708 bool is_non_native_row_major_matrix(uint32_t id) override;
709 bool member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index) override;
710 std::string convert_row_major_matrix(std::string exp_str, const SPIRType &exp_type, uint32_t physical_type_id,
711 bool is_packed) override;
712
713 void preprocess_op_codes();
714 void localize_global_variables();
715 void extract_global_variables_from_functions();
716 void mark_packable_structs();
717 void mark_as_packable(SPIRType &type);
718
719 std::unordered_map<uint32_t, std::set<uint32_t>> function_global_vars;
720 void extract_global_variables_from_function(uint32_t func_id, std::set<uint32_t> &added_arg_ids,
721 std::unordered_set<uint32_t> &global_var_ids,
722 std::unordered_set<uint32_t> &processed_func_ids);
723 uint32_t add_interface_block(spv::StorageClass storage, bool patch = false);
724 uint32_t add_interface_block_pointer(uint32_t ib_var_id, spv::StorageClass storage);
725
726 struct InterfaceBlockMeta
727 {
728 struct LocationMeta
729 {
730 uint32_t num_components = 0;
731 uint32_t ib_index = ~0u;
732 };
733 std::unordered_map<uint32_t, LocationMeta> location_meta;
734 bool strip_array = false;
735 };
736
737 void add_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref, SPIRType &ib_type,
738 SPIRVariable &var, InterfaceBlockMeta &meta);
739 void add_composite_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
740 SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta);
741 void add_plain_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
742 SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta);
743 void add_plain_member_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
744 SPIRType &ib_type, SPIRVariable &var, uint32_t index,
745 InterfaceBlockMeta &meta);
746 void add_composite_member_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
747 SPIRType &ib_type, SPIRVariable &var, uint32_t index,
748 InterfaceBlockMeta &meta);
749 uint32_t get_accumulated_member_location(const SPIRVariable &var, uint32_t mbr_idx, bool strip_array);
750 void add_tess_level_input_to_interface_block(const std::string &ib_var_ref, SPIRType &ib_type, SPIRVariable &var);
751
752 void fix_up_interface_member_indices(spv::StorageClass storage, uint32_t ib_type_id);
753
754 void mark_location_as_used_by_shader(uint32_t location, const SPIRType &type, spv::StorageClass storage);
755 uint32_t ensure_correct_builtin_type(uint32_t type_id, spv::BuiltIn builtin);
756 uint32_t ensure_correct_input_type(uint32_t type_id, uint32_t location, uint32_t num_components = 0);
757
758 void emit_custom_templates();
759 void emit_custom_functions();
760 void emit_resources();
761 void emit_specialization_constants_and_structs();
762 void emit_interface_block(uint32_t ib_var_id);
763 bool maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs);
764 uint32_t get_resource_array_size(uint32_t id) const;
765
766 void fix_up_shader_inputs_outputs();
767
768 std::string func_type_decl(SPIRType &type);
769 std::string entry_point_args_classic(bool append_comma);
770 std::string entry_point_args_argument_buffer(bool append_comma);
771 std::string entry_point_arg_stage_in();
772 void entry_point_args_builtin(std::string &args);
773 void entry_point_args_discrete_descriptors(std::string &args);
774 std::string to_qualified_member_name(const SPIRType &type, uint32_t index);
775 std::string ensure_valid_name(std::string name, std::string pfx);
776 std::string to_sampler_expression(uint32_t id);
777 std::string to_swizzle_expression(uint32_t id);
778 std::string to_buffer_size_expression(uint32_t id);
779 bool is_direct_input_builtin(spv::BuiltIn builtin);
780 std::string builtin_qualifier(spv::BuiltIn builtin);
781 std::string builtin_type_decl(spv::BuiltIn builtin, uint32_t id = 0);
782 std::string built_in_func_arg(spv::BuiltIn builtin, bool prefix_comma);
783 std::string member_attribute_qualifier(const SPIRType &type, uint32_t index);
784 std::string argument_decl(const SPIRFunction::Parameter &arg);
785 std::string round_fp_tex_coords(std::string tex_coords, bool coord_is_fp);
786 uint32_t get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane = 0);
787 uint32_t get_ordered_member_location(uint32_t type_id, uint32_t index, uint32_t *comp = nullptr);
788
789 // MSL packing rules. These compute the effective packing rules as observed by the MSL compiler in the MSL output.
790 // These values can change depending on various extended decorations which control packing rules.
791 // We need to make these rules match up with SPIR-V declared rules.
792 uint32_t get_declared_type_size_msl(const SPIRType &type, bool packed, bool row_major) const;
793 uint32_t get_declared_type_array_stride_msl(const SPIRType &type, bool packed, bool row_major) const;
794 uint32_t get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const;
795 uint32_t get_declared_type_alignment_msl(const SPIRType &type, bool packed, bool row_major) const;
796
797 uint32_t get_declared_struct_member_size_msl(const SPIRType &struct_type, uint32_t index) const;
798 uint32_t get_declared_struct_member_array_stride_msl(const SPIRType &struct_type, uint32_t index) const;
799 uint32_t get_declared_struct_member_matrix_stride_msl(const SPIRType &struct_type, uint32_t index) const;
800 uint32_t get_declared_struct_member_alignment_msl(const SPIRType &struct_type, uint32_t index) const;
801
802 uint32_t get_declared_input_size_msl(const SPIRType &struct_type, uint32_t index) const;
803 uint32_t get_declared_input_array_stride_msl(const SPIRType &struct_type, uint32_t index) const;
804 uint32_t get_declared_input_matrix_stride_msl(const SPIRType &struct_type, uint32_t index) const;
805 uint32_t get_declared_input_alignment_msl(const SPIRType &struct_type, uint32_t index) const;
806
807 const SPIRType &get_physical_member_type(const SPIRType &struct_type, uint32_t index) const;
808 SPIRType get_presumed_input_type(const SPIRType &struct_type, uint32_t index) const;
809
810 uint32_t get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment = false,
811 bool ignore_padding = false) const;
812
813 std::string to_component_argument(uint32_t id);
814 void align_struct(SPIRType &ib_type, std::unordered_set<uint32_t> &aligned_structs);
815 void mark_scalar_layout_structs(const SPIRType &ib_type);
816 void mark_struct_members_packed(const SPIRType &type);
817 void ensure_member_packing_rules_msl(SPIRType &ib_type, uint32_t index);
818 bool validate_member_packing_rules_msl(const SPIRType &type, uint32_t index) const;
819 std::string get_argument_address_space(const SPIRVariable &argument);
820 std::string get_type_address_space(const SPIRType &type, uint32_t id, bool argument = false);
821 const char *to_restrict(uint32_t id, bool space = true);
822 SPIRType &get_stage_in_struct_type();
823 SPIRType &get_stage_out_struct_type();
824 SPIRType &get_patch_stage_in_struct_type();
825 SPIRType &get_patch_stage_out_struct_type();
826 std::string get_tess_factor_struct_name();
827 SPIRType &get_uint_type();
828 uint32_t get_uint_type_id();
829 void emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, uint32_t mem_order_1,
830 uint32_t mem_order_2, bool has_mem_order_2, uint32_t op0, uint32_t op1 = 0,
831 bool op1_is_pointer = false, bool op1_is_literal = false, uint32_t op2 = 0);
832 const char *get_memory_order(uint32_t spv_mem_sem);
833 void add_pragma_line(const std::string &line);
834 void add_typedef_line(const std::string &line);
835 void emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem);
836 void emit_array_copy(const std::string &lhs, uint32_t rhs_id, spv::StorageClass lhs_storage,
837 spv::StorageClass rhs_storage) override;
838 void build_implicit_builtins();
839 uint32_t build_constant_uint_array_pointer();
840 void emit_entry_point_declarations() override;
841 uint32_t builtin_frag_coord_id = 0;
842 uint32_t builtin_sample_id_id = 0;
843 uint32_t builtin_sample_mask_id = 0;
844 uint32_t builtin_vertex_idx_id = 0;
845 uint32_t builtin_base_vertex_id = 0;
846 uint32_t builtin_instance_idx_id = 0;
847 uint32_t builtin_base_instance_id = 0;
848 uint32_t builtin_view_idx_id = 0;
849 uint32_t builtin_layer_id = 0;
850 uint32_t builtin_invocation_id_id = 0;
851 uint32_t builtin_primitive_id_id = 0;
852 uint32_t builtin_subgroup_invocation_id_id = 0;
853 uint32_t builtin_subgroup_size_id = 0;
854 uint32_t builtin_dispatch_base_id = 0;
855 uint32_t builtin_stage_input_size_id = 0;
856 uint32_t swizzle_buffer_id = 0;
857 uint32_t buffer_size_buffer_id = 0;
858 uint32_t view_mask_buffer_id = 0;
859 uint32_t dynamic_offsets_buffer_id = 0;
860 uint32_t uint_type_id = 0;
861
862 bool does_shader_write_sample_mask = false;
863
864 void cast_to_builtin_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type) override;
865 void cast_from_builtin_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type) override;
866 void emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression) override;
867
868 void analyze_sampled_image_usage();
869
870 void prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type, spv::StorageClass storage,
871 bool &is_packed) override;
872 void fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length);
873 bool emit_tessellation_access_chain(const uint32_t *ops, uint32_t length);
874 bool emit_tessellation_io_load(uint32_t result_type, uint32_t id, uint32_t ptr);
875 bool is_out_of_bounds_tessellation_level(uint32_t id_lhs);
876
877 void ensure_builtin(spv::StorageClass storage, spv::BuiltIn builtin);
878
879 void mark_implicit_builtin(spv::StorageClass storage, spv::BuiltIn builtin, uint32_t id);
880
881 std::string convert_to_f32(const std::string &expr, uint32_t components);
882
883 Options msl_options;
884 std::set<SPVFuncImpl> spv_function_implementations;
885 // Must be ordered to ensure declarations are in a specific order.
886 std::map<uint32_t, MSLShaderInput> inputs_by_location;
887 std::unordered_map<uint32_t, MSLShaderInput> inputs_by_builtin;
888 std::unordered_set<uint32_t> inputs_in_use;
889 std::unordered_map<uint32_t, uint32_t> fragment_output_components;
890 std::set<std::string> pragma_lines;
891 std::set<std::string> typedef_lines;
892 SmallVector<uint32_t> vars_needing_early_declaration;
893
894 std::unordered_map<StageSetBinding, std::pair<MSLResourceBinding, bool>, InternalHasher> resource_bindings;
895
896 uint32_t next_metal_resource_index_buffer = 0;
897 uint32_t next_metal_resource_index_texture = 0;
898 uint32_t next_metal_resource_index_sampler = 0;
899 // Intentionally uninitialized, works around MSVC 2013 bug.
900 uint32_t next_metal_resource_ids[kMaxArgumentBuffers];
901
902 VariableID stage_in_var_id = 0;
903 VariableID stage_out_var_id = 0;
904 VariableID patch_stage_in_var_id = 0;
905 VariableID patch_stage_out_var_id = 0;
906 VariableID stage_in_ptr_var_id = 0;
907 VariableID stage_out_ptr_var_id = 0;
908
909 // Handle HLSL-style 0-based vertex/instance index.
910 enum class TriState
911 {
912 Neutral,
913 No,
914 Yes
915 };
916 TriState needs_base_vertex_arg = TriState::Neutral;
917 TriState needs_base_instance_arg = TriState::Neutral;
918
919 bool has_sampled_images = false;
920 bool builtin_declaration = false; // Handle HLSL-style 0-based vertex/instance index.
921
922 bool is_using_builtin_array = false; // Force the use of C style array declaration.
923 bool using_builtin_array() const;
924
925 bool is_rasterization_disabled = false;
926 bool capture_output_to_buffer = false;
927 bool needs_swizzle_buffer_def = false;
928 bool used_swizzle_buffer = false;
929 bool added_builtin_tess_level = false;
930 bool needs_subgroup_invocation_id = false;
931 bool needs_subgroup_size = false;
932 bool needs_sample_id = false;
933 std::string qual_pos_var_name;
934 std::string stage_in_var_name = "in";
935 std::string stage_out_var_name = "out";
936 std::string patch_stage_in_var_name = "patchIn";
937 std::string patch_stage_out_var_name = "patchOut";
938 std::string sampler_name_suffix = "Smplr";
939 std::string swizzle_name_suffix = "Swzl";
940 std::string buffer_size_name_suffix = "BufferSize";
941 std::string plane_name_suffix = "Plane";
942 std::string input_wg_var_name = "gl_in";
943 std::string input_buffer_var_name = "spvIn";
944 std::string output_buffer_var_name = "spvOut";
945 std::string patch_output_buffer_var_name = "spvPatchOut";
946 std::string tess_factor_buffer_var_name = "spvTessLevel";
947 std::string index_buffer_var_name = "spvIndices";
948 spv::Op previous_instruction_opcode = spv::OpNop;
949
950 // Must be ordered since declaration is in a specific order.
951 std::map<uint32_t, MSLConstexprSampler> constexpr_samplers_by_id;
952 std::unordered_map<SetBindingPair, MSLConstexprSampler, InternalHasher> constexpr_samplers_by_binding;
953 const MSLConstexprSampler *find_constexpr_sampler(uint32_t id) const;
954
955 std::unordered_set<uint32_t> buffers_requiring_array_length;
956 SmallVector<uint32_t> buffer_arrays;
957 std::unordered_set<uint32_t> atomic_image_vars; // Emulate texture2D atomic operations
958 std::unordered_set<uint32_t> pull_model_inputs;
959
960 // Must be ordered since array is in a specific order.
961 std::map<SetBindingPair, std::pair<uint32_t, uint32_t>> buffers_requiring_dynamic_offset;
962
963 SmallVector<uint32_t> disabled_frag_outputs;
964
965 std::unordered_set<SetBindingPair, InternalHasher> inline_uniform_blocks;
966
967 uint32_t argument_buffer_ids[kMaxArgumentBuffers];
968 uint32_t argument_buffer_discrete_mask = 0;
969 uint32_t argument_buffer_device_storage_mask = 0;
970
971 void analyze_argument_buffers();
972 bool descriptor_set_is_argument_buffer(uint32_t desc_set) const;
973
974 uint32_t get_target_components_for_fragment_location(uint32_t location) const;
975 uint32_t build_extended_vector_type(uint32_t type_id, uint32_t components,
976 SPIRType::BaseType basetype = SPIRType::Unknown);
977 uint32_t build_msl_interpolant_type(uint32_t type_id, bool is_noperspective);
978
979 bool suppress_missing_prototypes = false;
980
981 void add_spv_func_and_recompile(SPVFuncImpl spv_func);
982
983 void activate_argument_buffer_resources();
984
985 bool type_is_msl_framebuffer_fetch(const SPIRType &type) const;
986
987 // OpcodeHandler that handles several MSL preprocessing operations.
988 struct OpCodePreprocessor : OpcodeHandler
989 {
990 OpCodePreprocessor(CompilerMSL &compiler_)
991 : compiler(compiler_)
992 {
993 }
994
995 bool handle(spv::Op opcode, const uint32_t *args, uint32_t length) override;
996 CompilerMSL::SPVFuncImpl get_spv_func_impl(spv::Op opcode, const uint32_t *args);
997 void check_resource_write(uint32_t var_id);
998
999 CompilerMSL &compiler;
1000 std::unordered_map<uint32_t, uint32_t> result_types;
1001 std::unordered_map<uint32_t, uint32_t> image_pointers; // Emulate texture2D atomic operations
1002 bool suppress_missing_prototypes = false;
1003 bool uses_atomics = false;
1004 bool uses_resource_write = false;
1005 bool needs_subgroup_invocation_id = false;
1006 bool needs_subgroup_size = false;
1007 bool needs_sample_id = false;
1008 };
1009
1010 // OpcodeHandler that scans for uses of sampled images
1011 struct SampledImageScanner : OpcodeHandler
1012 {
1013 SampledImageScanner(CompilerMSL &compiler_)
1014 : compiler(compiler_)
1015 {
1016 }
1017
1018 bool handle(spv::Op opcode, const uint32_t *args, uint32_t) override;
1019
1020 CompilerMSL &compiler;
1021 };
1022
1023 // Sorts the members of a SPIRType and associated Meta info based on a settable sorting
1024 // aspect, which defines which aspect of the struct members will be used to sort them.
1025 // Regardless of the sorting aspect, built-in members always appear at the end of the struct.
1026 struct MemberSorter
1027 {
1028 enum SortAspect
1029 {
1030 Location,
1031 LocationReverse,
1032 Offset,
1033 OffsetThenLocationReverse,
1034 Alphabetical
1035 };
1036
1037 void sort();
1038 bool operator()(uint32_t mbr_idx1, uint32_t mbr_idx2);
1039 MemberSorter(SPIRType &t, Meta &m, SortAspect sa);
1040
1041 SPIRType &type;
1042 Meta &meta;
1043 SortAspect sort_aspect;
1044 };
1045 };
1046 } // namespace SPIRV_CROSS_NAMESPACE
1047
1048 #endif