blob: 3828fc441b8fa622c916356b9eecc021465d3113 [file] [log] [blame]
Bill Hollings103aabf2016-04-06 17:42:27 -04001/*
Hans-Kristian Arntzen47044822021-01-14 16:07:49 +01002 * Copyright 2016-2021 The Brenwill Workshop Ltd.
Jon Leechf2a65542021-05-08 01:47:48 -07003 * SPDX-License-Identifier: Apache-2.0 OR MIT
Bill Hollings103aabf2016-04-06 17:42:27 -04004 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
Hans-Kristian Arntzencf1e9e02020-11-25 15:22:08 +010018/*
19 * At your option, you may choose to accept this material under either:
20 * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
21 * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
Hans-Kristian Arntzencf1e9e02020-11-25 15:22:08 +010022 */
23
Bill Hollings103aabf2016-04-06 17:42:27 -040024#include "spirv_msl.hpp"
Bill Hollingsf5f91042016-10-27 18:47:17 -040025#include "GLSL.std.450.h"
Corentin Wallez789eb432017-01-26 19:40:56 -050026
Bill Hollings103aabf2016-04-06 17:42:27 -040027#include <algorithm>
Hans-Kristian Arntzen702e0862018-02-09 12:13:33 +010028#include <assert.h>
Hans-Kristian Arntzen54a065b2018-02-15 13:32:49 +010029#include <numeric>
Bill Hollings103aabf2016-04-06 17:42:27 -040030
31using namespace spv;
Hans-Kristian Arntzen9b92e682019-03-29 10:29:44 +010032using namespace SPIRV_CROSS_NAMESPACE;
Bill Hollings103aabf2016-04-06 17:42:27 -040033using namespace std;
34
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +010035static const uint32_t k_unknown_location = ~0u;
Chip Davis4b99fdd2018-09-05 17:31:10 -050036static const uint32_t k_unknown_component = ~0u;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040037static const char *force_inline = "static inline __attribute__((always_inline))";
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +010038
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +020039CompilerMSL::CompilerMSL(std::vector<uint32_t> spirv_)
Bill Hollings7703b742017-04-04 16:38:17 -040040 : CompilerGLSL(move(spirv_))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020041{
Bill Hollings4a6358b2017-01-07 22:15:58 -050042}
43
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010044CompilerMSL::CompilerMSL(const uint32_t *ir_, size_t word_count)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020045 : CompilerGLSL(ir_, word_count)
46{
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020047}
48
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010049CompilerMSL::CompilerMSL(const ParsedIR &ir_)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020050 : CompilerGLSL(ir_)
51{
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020052}
53
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010054CompilerMSL::CompilerMSL(ParsedIR &&ir_)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020055 : CompilerGLSL(std::move(ir_))
Hans-Kristian Arntzen9bad4772017-04-01 16:08:19 +020056{
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010057}
Bill Hollings7703b742017-04-04 16:38:17 -040058
Chip Davis5281d992020-06-13 23:03:30 -050059void CompilerMSL::add_msl_shader_input(const MSLShaderInput &si)
60{
Bill Hollings548a23d2021-09-20 17:57:11 -040061 inputs_by_location[{si.location, si.component}] = si;
Chip Davis5281d992020-06-13 23:03:30 -050062 if (si.builtin != BuiltInMax && !inputs_by_builtin.count(si.builtin))
63 inputs_by_builtin[si.builtin] = si;
64}
65
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010066void CompilerMSL::add_msl_resource_binding(const MSLResourceBinding &binding)
67{
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020068 StageSetBinding tuple = { binding.stage, binding.desc_set, binding.binding };
69 resource_bindings[tuple] = { binding, false };
Bill Hollings9866cf42021-04-16 09:05:15 -040070
71 // If we might need to pad argument buffer members to positionally align
72 // arg buffer indexes, also maintain a lookup by argument buffer index.
73 if (msl_options.pad_argument_buffer_resources)
74 {
Bill Hollings9060e5a2021-04-16 15:00:59 -040075 StageSetBinding arg_idx_tuple = { binding.stage, binding.desc_set, k_unknown_component };
76
Bill Hollingsdaba0df2021-04-17 15:20:53 -040077#define ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(rez) \
78 arg_idx_tuple.binding = binding.msl_##rez; \
Bill Hollings9060e5a2021-04-16 15:00:59 -040079 resource_arg_buff_idx_to_binding_number[arg_idx_tuple] = binding.binding
80
Bill Hollingsb3bfe222021-04-18 17:34:55 -040081 switch (binding.basetype)
Bill Hollings9866cf42021-04-16 09:05:15 -040082 {
83 case SPIRType::Void:
Bill Hollingsb3bfe222021-04-18 17:34:55 -040084 case SPIRType::Boolean:
85 case SPIRType::SByte:
86 case SPIRType::UByte:
87 case SPIRType::Short:
88 case SPIRType::UShort:
89 case SPIRType::Int:
90 case SPIRType::UInt:
91 case SPIRType::Int64:
92 case SPIRType::UInt64:
93 case SPIRType::AtomicCounter:
94 case SPIRType::Half:
95 case SPIRType::Float:
96 case SPIRType::Double:
Bill Hollings9060e5a2021-04-16 15:00:59 -040097 ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(buffer);
Bill Hollings9866cf42021-04-16 09:05:15 -040098 break;
99 case SPIRType::Image:
Bill Hollings9060e5a2021-04-16 15:00:59 -0400100 ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture);
Bill Hollings9866cf42021-04-16 09:05:15 -0400101 break;
102 case SPIRType::Sampler:
Bill Hollings9060e5a2021-04-16 15:00:59 -0400103 ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler);
104 break;
105 case SPIRType::SampledImage:
106 ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(texture);
107 ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP(sampler);
Bill Hollings9866cf42021-04-16 09:05:15 -0400108 break;
109 default:
110 SPIRV_CROSS_THROW("Unexpected argument buffer resource base type. When padding argument buffer elements, "
111 "all descriptor set resources must be supplied with a base type by the app.");
Bill Hollings9866cf42021-04-16 09:05:15 -0400112 }
Bill Hollings9060e5a2021-04-16 15:00:59 -0400113#undef ADD_ARG_IDX_TO_BINDING_NUM_LOOKUP
Bill Hollings9866cf42021-04-16 09:05:15 -0400114 }
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +0100115}
116
Chip Daviscb359342019-09-05 23:14:12 -0500117void CompilerMSL::add_dynamic_buffer(uint32_t desc_set, uint32_t binding, uint32_t index)
118{
119 SetBindingPair pair = { desc_set, binding };
120 buffers_requiring_dynamic_offset[pair] = { index, 0 };
121}
122
Chip Davisfedbc352019-12-16 22:58:16 -0600123void CompilerMSL::add_inline_uniform_block(uint32_t desc_set, uint32_t binding)
124{
125 SetBindingPair pair = { desc_set, binding };
126 inline_uniform_blocks.insert(pair);
127}
128
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +0100129void CompilerMSL::add_discrete_descriptor_set(uint32_t desc_set)
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +0100130{
131 if (desc_set < kMaxArgumentBuffers)
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +0100132 argument_buffer_discrete_mask |= 1u << desc_set;
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +0100133}
134
Hans-Kristian Arntzen4bb673a2019-10-14 12:51:48 +0200135void CompilerMSL::set_argument_buffer_device_address_space(uint32_t desc_set, bool device_storage)
136{
137 if (desc_set < kMaxArgumentBuffers)
138 {
139 if (device_storage)
140 argument_buffer_device_storage_mask |= 1u << desc_set;
141 else
142 argument_buffer_device_storage_mask &= ~(1u << desc_set);
143 }
144}
145
Chip Davis5281d992020-06-13 23:03:30 -0500146bool CompilerMSL::is_msl_shader_input_used(uint32_t location)
147{
Hans-Kristian Arntzenfaf80b02021-04-09 18:55:10 +0200148 // Don't report internal location allocations to app.
149 return location_inputs_in_use.count(location) != 0 &&
150 location_inputs_in_use_fallback.count(location) == 0;
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +0100151}
152
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +0100153uint32_t CompilerMSL::get_automatic_builtin_input_location(spv::BuiltIn builtin) const
154{
155 auto itr = builtin_to_automatic_input_location.find(builtin);
156 if (itr == builtin_to_automatic_input_location.end())
157 return k_unknown_location;
158 else
159 return itr->second;
160}
161
Hans-Kristian Arntzencc153f82020-01-09 11:18:14 +0100162bool CompilerMSL::is_msl_resource_binding_used(ExecutionModel model, uint32_t desc_set, uint32_t binding) const
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +0100163{
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +0200164 StageSetBinding tuple = { model, desc_set, binding };
165 auto itr = resource_bindings.find(tuple);
166 return itr != end(resource_bindings) && itr->second.second;
Hans-Kristian Arntzen9bad4772017-04-01 16:08:19 +0200167}
168
Bill Hollings4bdd49d2020-11-02 22:15:20 -0500169// Returns the size of the array of resources used by the variable with the specified id.
170// The returned value is retrieved from the resource binding added using add_msl_resource_binding().
Bill Hollingsb7b0e802020-10-29 18:50:42 -0400171uint32_t CompilerMSL::get_resource_array_size(uint32_t id) const
172{
Bill Hollings7f67abe2020-10-30 16:05:44 -0400173 StageSetBinding tuple = { get_entry_point().model, get_decoration(id, DecorationDescriptorSet),
174 get_decoration(id, DecorationBinding) };
Bill Hollingsb7b0e802020-10-29 18:50:42 -0400175 auto itr = resource_bindings.find(tuple);
Bill Hollings4bdd49d2020-11-02 22:15:20 -0500176 return itr != end(resource_bindings) ? itr->second.first.count : 0;
Bill Hollingsb7b0e802020-10-29 18:50:42 -0400177}
178
Hans-Kristian Arntzen3a4a9ac2019-06-21 13:19:59 +0200179uint32_t CompilerMSL::get_automatic_msl_resource_binding(uint32_t id) const
180{
181 return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexPrimary);
182}
183
184uint32_t CompilerMSL::get_automatic_msl_resource_binding_secondary(uint32_t id) const
185{
186 return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexSecondary);
187}
188
Chip Davis39dce882019-08-02 15:11:19 -0500189uint32_t CompilerMSL::get_automatic_msl_resource_binding_tertiary(uint32_t id) const
190{
191 return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexTertiary);
192}
193
194uint32_t CompilerMSL::get_automatic_msl_resource_binding_quaternary(uint32_t id) const
195{
196 return get_extended_decoration(id, SPIRVCrossDecorationResourceIndexQuaternary);
197}
198
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +0100199void CompilerMSL::set_fragment_output_components(uint32_t location, uint32_t components)
200{
201 fragment_output_components[location] = components;
202}
203
Lukas Hermanns6673a672019-10-22 11:06:16 -0400204bool CompilerMSL::builtin_translates_to_nonarray(spv::BuiltIn builtin) const
205{
206 return (builtin == BuiltInSampleMask);
207}
208
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100209void CompilerMSL::build_implicit_builtins()
210{
Chip Davis39bc1012018-09-12 14:05:52 -0500211 bool need_sample_pos = active_input_builtins.get(BuiltInSamplePosition);
Chip Davis688c5fc2020-02-20 21:38:28 -0600212 bool need_vertex_params = capture_output_to_buffer && get_execution_model() == ExecutionModelVertex &&
213 !msl_options.vertex_for_tessellation;
Chip Daviseb89c3a2019-02-03 23:58:46 -0600214 bool need_tesc_params = get_execution_model() == ExecutionModelTessellationControl;
Chip Davis9d941572019-05-15 16:03:30 -0500215 bool need_subgroup_mask =
216 active_input_builtins.get(BuiltInSubgroupEqMask) || active_input_builtins.get(BuiltInSubgroupGeMask) ||
217 active_input_builtins.get(BuiltInSubgroupGtMask) || active_input_builtins.get(BuiltInSubgroupLeMask) ||
218 active_input_builtins.get(BuiltInSubgroupLtMask);
219 bool need_subgroup_ge_mask = !msl_options.is_ios() && (active_input_builtins.get(BuiltInSubgroupGeMask) ||
220 active_input_builtins.get(BuiltInSubgroupGtMask));
Chip Davis6a585542019-07-12 21:50:50 -0500221 bool need_multiview = get_execution_model() == ExecutionModelVertex && !msl_options.view_index_from_device_index &&
Chip Daviscab73352020-08-23 16:44:41 -0500222 msl_options.multiview_layered_rendering &&
Chip Davis7eecf5a2019-05-31 12:06:20 -0500223 (msl_options.multiview || active_input_builtins.get(BuiltInViewIndex));
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500224 bool need_dispatch_base =
225 msl_options.dispatch_base && get_execution_model() == ExecutionModelGLCompute &&
226 (active_input_builtins.get(BuiltInWorkgroupId) || active_input_builtins.get(BuiltInGlobalInvocationId));
Chip Davis688c5fc2020-02-20 21:38:28 -0600227 bool need_grid_params = get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation;
228 bool need_vertex_base_params =
229 need_grid_params &&
230 (active_input_builtins.get(BuiltInVertexId) || active_input_builtins.get(BuiltInVertexIndex) ||
231 active_input_builtins.get(BuiltInBaseVertex) || active_input_builtins.get(BuiltInInstanceId) ||
232 active_input_builtins.get(BuiltInInstanceIndex) || active_input_builtins.get(BuiltInBaseInstance));
Chip Davis68908352020-11-18 23:16:46 -0600233 bool need_local_invocation_index = msl_options.emulate_subgroups && active_input_builtins.get(BuiltInSubgroupId);
234 bool need_workgroup_size = msl_options.emulate_subgroups && active_input_builtins.get(BuiltInNumSubgroups);
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100235
Chip Davis9d941572019-05-15 16:03:30 -0500236 if (need_subpass_input || need_sample_pos || need_subgroup_mask || need_vertex_params || need_tesc_params ||
Chip Davisaca9b682020-11-02 20:56:46 -0600237 need_multiview || need_dispatch_base || need_vertex_base_params || need_grid_params || needs_sample_id ||
Bill Hollingsebb50982021-07-13 21:22:13 -0400238 needs_subgroup_invocation_id || needs_subgroup_size || has_additional_fixed_sample_mask() || need_local_invocation_index ||
Chip Davis68908352020-11-18 23:16:46 -0600239 need_workgroup_size)
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100240 {
241 bool has_frag_coord = false;
Chip Davis39bc1012018-09-12 14:05:52 -0500242 bool has_sample_id = false;
Chip Davisc51e5b72019-01-08 16:33:32 -0600243 bool has_vertex_idx = false;
244 bool has_base_vertex = false;
245 bool has_instance_idx = false;
246 bool has_base_instance = false;
Chip Daviseb89c3a2019-02-03 23:58:46 -0600247 bool has_invocation_id = false;
248 bool has_primitive_id = false;
Chip Davis9d941572019-05-15 16:03:30 -0500249 bool has_subgroup_invocation_id = false;
250 bool has_subgroup_size = false;
Chip Davis7eecf5a2019-05-31 12:06:20 -0500251 bool has_view_idx = false;
Chip Davis4cf840e2020-08-27 19:24:20 -0500252 bool has_layer = false;
Chip Davis68908352020-11-18 23:16:46 -0600253 bool has_local_invocation_index = false;
254 bool has_workgroup_size = false;
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500255 uint32_t workgroup_id_type = 0;
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100256
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +0100257 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
Hans-Kristian Arntzenfa76d012021-01-07 10:28:06 +0100258 if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
259 return;
260 if (!interface_variable_exists_in_entry_point(var.self))
261 return;
262 if (!has_decoration(var.self, DecorationBuiltIn))
Chip Davisc51e5b72019-01-08 16:33:32 -0600263 return;
264
Chip Davis9d941572019-05-15 16:03:30 -0500265 BuiltIn builtin = ir.meta[var.self].decoration.builtin_type;
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200266
267 if (var.storage == StorageClassOutput)
268 {
Bill Hollingsebb50982021-07-13 21:22:13 -0400269 if (has_additional_fixed_sample_mask() && builtin == BuiltInSampleMask)
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200270 {
271 builtin_sample_mask_id = var.self;
272 mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var.self);
273 does_shader_write_sample_mask = true;
274 }
275 }
276
277 if (var.storage != StorageClassInput)
278 return;
279
Chip Davis68908352020-11-18 23:16:46 -0600280 // Use Metal's native frame-buffer fetch API for subpass inputs.
Chip Davisc20d5942020-10-27 21:42:33 -0500281 if (need_subpass_input && (!msl_options.use_framebuffer_fetch_subpasses))
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100282 {
Chip Davis4cf840e2020-08-27 19:24:20 -0500283 switch (builtin)
284 {
285 case BuiltInFragCoord:
286 mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var.self);
287 builtin_frag_coord_id = var.self;
288 has_frag_coord = true;
289 break;
290 case BuiltInLayer:
291 if (!msl_options.arrayed_subpass_input || msl_options.multiview)
292 break;
293 mark_implicit_builtin(StorageClassInput, BuiltInLayer, var.self);
294 builtin_layer_id = var.self;
295 has_layer = true;
296 break;
297 case BuiltInViewIndex:
298 if (!msl_options.multiview)
299 break;
300 mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self);
301 builtin_view_idx_id = var.self;
302 has_view_idx = true;
303 break;
304 default:
305 break;
306 }
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100307 }
Chip Davis39bc1012018-09-12 14:05:52 -0500308
Chip Davisaca9b682020-11-02 20:56:46 -0600309 if ((need_sample_pos || needs_sample_id) && builtin == BuiltInSampleId)
Chip Davis39bc1012018-09-12 14:05:52 -0500310 {
311 builtin_sample_id_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200312 mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var.self);
Chip Davis39bc1012018-09-12 14:05:52 -0500313 has_sample_id = true;
Chip Davis39bc1012018-09-12 14:05:52 -0500314 }
Chip Davisc51e5b72019-01-08 16:33:32 -0600315
Chip Daviseb89c3a2019-02-03 23:58:46 -0600316 if (need_vertex_params)
Chip Davisc51e5b72019-01-08 16:33:32 -0600317 {
Chip Davis9d941572019-05-15 16:03:30 -0500318 switch (builtin)
Chip Davisc51e5b72019-01-08 16:33:32 -0600319 {
320 case BuiltInVertexIndex:
321 builtin_vertex_idx_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200322 mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var.self);
Chip Davisc51e5b72019-01-08 16:33:32 -0600323 has_vertex_idx = true;
324 break;
325 case BuiltInBaseVertex:
326 builtin_base_vertex_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200327 mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var.self);
Chip Davisc51e5b72019-01-08 16:33:32 -0600328 has_base_vertex = true;
329 break;
330 case BuiltInInstanceIndex:
331 builtin_instance_idx_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200332 mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self);
Chip Davisc51e5b72019-01-08 16:33:32 -0600333 has_instance_idx = true;
334 break;
335 case BuiltInBaseInstance:
336 builtin_base_instance_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200337 mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self);
Chip Davisc51e5b72019-01-08 16:33:32 -0600338 has_base_instance = true;
339 break;
340 default:
341 break;
342 }
343 }
Chip Daviseb89c3a2019-02-03 23:58:46 -0600344
345 if (need_tesc_params)
346 {
Chip Davis9d941572019-05-15 16:03:30 -0500347 switch (builtin)
Chip Daviseb89c3a2019-02-03 23:58:46 -0600348 {
349 case BuiltInInvocationId:
350 builtin_invocation_id_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200351 mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var.self);
Chip Daviseb89c3a2019-02-03 23:58:46 -0600352 has_invocation_id = true;
353 break;
354 case BuiltInPrimitiveId:
355 builtin_primitive_id_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200356 mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var.self);
Chip Daviseb89c3a2019-02-03 23:58:46 -0600357 has_primitive_id = true;
358 break;
359 default:
360 break;
361 }
362 }
Chip Davis9d941572019-05-15 16:03:30 -0500363
364 if ((need_subgroup_mask || needs_subgroup_invocation_id) && builtin == BuiltInSubgroupLocalInvocationId)
365 {
366 builtin_subgroup_invocation_id_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200367 mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var.self);
Chip Davis9d941572019-05-15 16:03:30 -0500368 has_subgroup_invocation_id = true;
369 }
370
Chip Davis065b5bd2020-10-20 23:59:30 -0500371 if ((need_subgroup_ge_mask || needs_subgroup_size) && builtin == BuiltInSubgroupSize)
Chip Davis9d941572019-05-15 16:03:30 -0500372 {
373 builtin_subgroup_size_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200374 mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var.self);
Chip Davis9d941572019-05-15 16:03:30 -0500375 has_subgroup_size = true;
376 }
Chip Davis7eecf5a2019-05-31 12:06:20 -0500377
378 if (need_multiview)
379 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400380 switch (builtin)
Chip Davis7eecf5a2019-05-31 12:06:20 -0500381 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400382 case BuiltInInstanceIndex:
Chip Davis7eecf5a2019-05-31 12:06:20 -0500383 // The view index here is derived from the instance index.
384 builtin_instance_idx_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200385 mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var.self);
Chip Davis7eecf5a2019-05-31 12:06:20 -0500386 has_instance_idx = true;
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400387 break;
Chip Davis53080ec2020-08-07 17:46:28 -0500388 case BuiltInBaseInstance:
389 // If a non-zero base instance is used, we need to adjust for it when calculating the view index.
390 builtin_base_instance_id = var.self;
391 mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var.self);
392 has_base_instance = true;
393 break;
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400394 case BuiltInViewIndex:
Chip Davis7eecf5a2019-05-31 12:06:20 -0500395 builtin_view_idx_id = var.self;
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200396 mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var.self);
Chip Davis7eecf5a2019-05-31 12:06:20 -0500397 has_view_idx = true;
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400398 break;
399 default:
400 break;
Chip Davis7eecf5a2019-05-31 12:06:20 -0500401 }
402 }
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500403
Chip Davis68908352020-11-18 23:16:46 -0600404 if (need_local_invocation_index && builtin == BuiltInLocalInvocationIndex)
405 {
406 builtin_local_invocation_index_id = var.self;
407 mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var.self);
408 has_local_invocation_index = true;
409 }
410
411 if (need_workgroup_size && builtin == BuiltInLocalInvocationId)
412 {
413 builtin_workgroup_size_id = var.self;
414 mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var.self);
415 has_workgroup_size = true;
416 }
417
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500418 // The base workgroup needs to have the same type and vector size
419 // as the workgroup or invocation ID, so keep track of the type that
420 // was used.
421 if (need_dispatch_base && workgroup_id_type == 0 &&
422 (builtin == BuiltInWorkgroupId || builtin == BuiltInGlobalInvocationId))
423 workgroup_id_type = var.basetype;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +0100424 });
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100425
Lukas Hermanns50ac6862019-09-18 14:03:54 -0400426 // Use Metal's native frame-buffer fetch API for subpass inputs.
Chip Davis4cf840e2020-08-27 19:24:20 -0500427 if ((!has_frag_coord || (msl_options.multiview && !has_view_idx) ||
428 (msl_options.arrayed_subpass_input && !msl_options.multiview && !has_layer)) &&
Chip Davisc20d5942020-10-27 21:42:33 -0500429 (!msl_options.use_framebuffer_fetch_subpasses) && need_subpass_input)
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100430 {
Chip Davis4cf840e2020-08-27 19:24:20 -0500431 if (!has_frag_coord)
432 {
433 uint32_t offset = ir.increase_bound_by(3);
434 uint32_t type_id = offset;
435 uint32_t type_ptr_id = offset + 1;
436 uint32_t var_id = offset + 2;
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100437
Chip Davis4cf840e2020-08-27 19:24:20 -0500438 // Create gl_FragCoord.
439 SPIRType vec4_type;
440 vec4_type.basetype = SPIRType::Float;
441 vec4_type.width = 32;
442 vec4_type.vecsize = 4;
443 set<SPIRType>(type_id, vec4_type);
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100444
Chip Davis4cf840e2020-08-27 19:24:20 -0500445 SPIRType vec4_type_ptr;
446 vec4_type_ptr = vec4_type;
447 vec4_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100448 vec4_type_ptr.pointer_depth++;
Chip Davis4cf840e2020-08-27 19:24:20 -0500449 vec4_type_ptr.parent_type = type_id;
450 vec4_type_ptr.storage = StorageClassInput;
451 auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr);
452 ptr_type.self = type_id;
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100453
Chip Davis4cf840e2020-08-27 19:24:20 -0500454 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
455 set_decoration(var_id, DecorationBuiltIn, BuiltInFragCoord);
456 builtin_frag_coord_id = var_id;
457 mark_implicit_builtin(StorageClassInput, BuiltInFragCoord, var_id);
458 }
459
460 if (!has_layer && msl_options.arrayed_subpass_input && !msl_options.multiview)
461 {
462 uint32_t offset = ir.increase_bound_by(2);
463 uint32_t type_ptr_id = offset;
464 uint32_t var_id = offset + 1;
465
466 // Create gl_Layer.
467 SPIRType uint_type_ptr;
468 uint_type_ptr = get_uint_type();
469 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100470 uint_type_ptr.pointer_depth++;
Chip Davis4cf840e2020-08-27 19:24:20 -0500471 uint_type_ptr.parent_type = get_uint_type_id();
472 uint_type_ptr.storage = StorageClassInput;
473 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
474 ptr_type.self = get_uint_type_id();
475
476 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
477 set_decoration(var_id, DecorationBuiltIn, BuiltInLayer);
478 builtin_layer_id = var_id;
479 mark_implicit_builtin(StorageClassInput, BuiltInLayer, var_id);
480 }
481
482 if (!has_view_idx && msl_options.multiview)
483 {
484 uint32_t offset = ir.increase_bound_by(2);
485 uint32_t type_ptr_id = offset;
486 uint32_t var_id = offset + 1;
487
488 // Create gl_ViewIndex.
489 SPIRType uint_type_ptr;
490 uint_type_ptr = get_uint_type();
491 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100492 uint_type_ptr.pointer_depth++;
Chip Davis4cf840e2020-08-27 19:24:20 -0500493 uint_type_ptr.parent_type = get_uint_type_id();
494 uint_type_ptr.storage = StorageClassInput;
495 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
496 ptr_type.self = get_uint_type_id();
497
498 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
499 set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex);
500 builtin_view_idx_id = var_id;
501 mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id);
502 }
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100503 }
Chip Davis39bc1012018-09-12 14:05:52 -0500504
Chip Davisaca9b682020-11-02 20:56:46 -0600505 if (!has_sample_id && (need_sample_pos || needs_sample_id))
Chip Davis39bc1012018-09-12 14:05:52 -0500506 {
Chip Davis884bc6d2020-07-22 15:25:10 -0600507 uint32_t offset = ir.increase_bound_by(2);
508 uint32_t type_ptr_id = offset;
509 uint32_t var_id = offset + 1;
Chip Davis39bc1012018-09-12 14:05:52 -0500510
511 // Create gl_SampleID.
Chip Davis39bc1012018-09-12 14:05:52 -0500512 SPIRType uint_type_ptr;
Chip Davis884bc6d2020-07-22 15:25:10 -0600513 uint_type_ptr = get_uint_type();
Chip Davis39bc1012018-09-12 14:05:52 -0500514 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100515 uint_type_ptr.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600516 uint_type_ptr.parent_type = get_uint_type_id();
Chip Davis39bc1012018-09-12 14:05:52 -0500517 uint_type_ptr.storage = StorageClassInput;
518 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
Chip Davis884bc6d2020-07-22 15:25:10 -0600519 ptr_type.self = get_uint_type_id();
Chip Davis39bc1012018-09-12 14:05:52 -0500520
521 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
522 set_decoration(var_id, DecorationBuiltIn, BuiltInSampleId);
523 builtin_sample_id_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200524 mark_implicit_builtin(StorageClassInput, BuiltInSampleId, var_id);
Chip Davis39bc1012018-09-12 14:05:52 -0500525 }
Chip Davisc51e5b72019-01-08 16:33:32 -0600526
Chip Davis7eecf5a2019-05-31 12:06:20 -0500527 if ((need_vertex_params && (!has_vertex_idx || !has_base_vertex || !has_instance_idx || !has_base_instance)) ||
Chip Davis53080ec2020-08-07 17:46:28 -0500528 (need_multiview && (!has_instance_idx || !has_base_instance || !has_view_idx)))
Chip Davisc51e5b72019-01-08 16:33:32 -0600529 {
Chip Davis884bc6d2020-07-22 15:25:10 -0600530 uint32_t type_ptr_id = ir.increase_bound_by(1);
Chip Davisc51e5b72019-01-08 16:33:32 -0600531
532 SPIRType uint_type_ptr;
Chip Davis884bc6d2020-07-22 15:25:10 -0600533 uint_type_ptr = get_uint_type();
Chip Davisc51e5b72019-01-08 16:33:32 -0600534 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100535 uint_type_ptr.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600536 uint_type_ptr.parent_type = get_uint_type_id();
Chip Davisc51e5b72019-01-08 16:33:32 -0600537 uint_type_ptr.storage = StorageClassInput;
538 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
Chip Davis884bc6d2020-07-22 15:25:10 -0600539 ptr_type.self = get_uint_type_id();
Chip Davisc51e5b72019-01-08 16:33:32 -0600540
Chip Davis7eecf5a2019-05-31 12:06:20 -0500541 if (need_vertex_params && !has_vertex_idx)
Chip Davisc51e5b72019-01-08 16:33:32 -0600542 {
543 uint32_t var_id = ir.increase_bound_by(1);
544
545 // Create gl_VertexIndex.
546 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
547 set_decoration(var_id, DecorationBuiltIn, BuiltInVertexIndex);
548 builtin_vertex_idx_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200549 mark_implicit_builtin(StorageClassInput, BuiltInVertexIndex, var_id);
Chip Davisc51e5b72019-01-08 16:33:32 -0600550 }
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200551
Chip Davis7eecf5a2019-05-31 12:06:20 -0500552 if (need_vertex_params && !has_base_vertex)
Chip Davisc51e5b72019-01-08 16:33:32 -0600553 {
554 uint32_t var_id = ir.increase_bound_by(1);
555
556 // Create gl_BaseVertex.
557 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
558 set_decoration(var_id, DecorationBuiltIn, BuiltInBaseVertex);
559 builtin_base_vertex_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200560 mark_implicit_builtin(StorageClassInput, BuiltInBaseVertex, var_id);
Chip Davisc51e5b72019-01-08 16:33:32 -0600561 }
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200562
Chip Davis7eecf5a2019-05-31 12:06:20 -0500563 if (!has_instance_idx) // Needed by both multiview and tessellation
Chip Davisc51e5b72019-01-08 16:33:32 -0600564 {
565 uint32_t var_id = ir.increase_bound_by(1);
566
567 // Create gl_InstanceIndex.
568 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
569 set_decoration(var_id, DecorationBuiltIn, BuiltInInstanceIndex);
570 builtin_instance_idx_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200571 mark_implicit_builtin(StorageClassInput, BuiltInInstanceIndex, var_id);
Chip Davisc51e5b72019-01-08 16:33:32 -0600572 }
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200573
Chip Davis53080ec2020-08-07 17:46:28 -0500574 if (!has_base_instance) // Needed by both multiview and tessellation
Chip Davisc51e5b72019-01-08 16:33:32 -0600575 {
576 uint32_t var_id = ir.increase_bound_by(1);
577
578 // Create gl_BaseInstance.
579 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
580 set_decoration(var_id, DecorationBuiltIn, BuiltInBaseInstance);
581 builtin_base_instance_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200582 mark_implicit_builtin(StorageClassInput, BuiltInBaseInstance, var_id);
Chip Davisc51e5b72019-01-08 16:33:32 -0600583 }
Chip Davis7eecf5a2019-05-31 12:06:20 -0500584
Chip Davis6a585542019-07-12 21:50:50 -0500585 if (need_multiview)
586 {
587 // Multiview shaders are not allowed to write to gl_Layer, ostensibly because
588 // it is implicitly written from gl_ViewIndex, but we have to do that explicitly.
589 // Note that we can't just abuse gl_ViewIndex for this purpose: it's an input, but
590 // gl_Layer is an output in vertex-pipeline shaders.
591 uint32_t type_ptr_out_id = ir.increase_bound_by(2);
592 SPIRType uint_type_ptr_out;
Chip Davis884bc6d2020-07-22 15:25:10 -0600593 uint_type_ptr_out = get_uint_type();
Chip Davis6a585542019-07-12 21:50:50 -0500594 uint_type_ptr_out.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100595 uint_type_ptr_out.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600596 uint_type_ptr_out.parent_type = get_uint_type_id();
Chip Davis6a585542019-07-12 21:50:50 -0500597 uint_type_ptr_out.storage = StorageClassOutput;
598 auto &ptr_out_type = set<SPIRType>(type_ptr_out_id, uint_type_ptr_out);
Chip Davis884bc6d2020-07-22 15:25:10 -0600599 ptr_out_type.self = get_uint_type_id();
Chip Davis6a585542019-07-12 21:50:50 -0500600 uint32_t var_id = type_ptr_out_id + 1;
601 set<SPIRVariable>(var_id, type_ptr_out_id, StorageClassOutput);
602 set_decoration(var_id, DecorationBuiltIn, BuiltInLayer);
603 builtin_layer_id = var_id;
604 mark_implicit_builtin(StorageClassOutput, BuiltInLayer, var_id);
605 }
606
Chip Davis7eecf5a2019-05-31 12:06:20 -0500607 if (need_multiview && !has_view_idx)
608 {
609 uint32_t var_id = ir.increase_bound_by(1);
610
611 // Create gl_ViewIndex.
612 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
613 set_decoration(var_id, DecorationBuiltIn, BuiltInViewIndex);
614 builtin_view_idx_id = var_id;
615 mark_implicit_builtin(StorageClassInput, BuiltInViewIndex, var_id);
616 }
Chip Davisc51e5b72019-01-08 16:33:32 -0600617 }
Chip Daviseb89c3a2019-02-03 23:58:46 -0600618
Chip Davis688c5fc2020-02-20 21:38:28 -0600619 if ((need_tesc_params && (msl_options.multi_patch_workgroup || !has_invocation_id || !has_primitive_id)) ||
620 need_grid_params)
Chip Daviseb89c3a2019-02-03 23:58:46 -0600621 {
Chip Davis884bc6d2020-07-22 15:25:10 -0600622 uint32_t type_ptr_id = ir.increase_bound_by(1);
Chip Daviseb89c3a2019-02-03 23:58:46 -0600623
624 SPIRType uint_type_ptr;
Chip Davis884bc6d2020-07-22 15:25:10 -0600625 uint_type_ptr = get_uint_type();
Chip Daviseb89c3a2019-02-03 23:58:46 -0600626 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100627 uint_type_ptr.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600628 uint_type_ptr.parent_type = get_uint_type_id();
Chip Daviseb89c3a2019-02-03 23:58:46 -0600629 uint_type_ptr.storage = StorageClassInput;
630 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
Chip Davis884bc6d2020-07-22 15:25:10 -0600631 ptr_type.self = get_uint_type_id();
Chip Daviseb89c3a2019-02-03 23:58:46 -0600632
Chip Davis688c5fc2020-02-20 21:38:28 -0600633 if (msl_options.multi_patch_workgroup || need_grid_params)
634 {
635 uint32_t var_id = ir.increase_bound_by(1);
636
637 // Create gl_GlobalInvocationID.
638 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
639 set_decoration(var_id, DecorationBuiltIn, BuiltInGlobalInvocationId);
640 builtin_invocation_id_id = var_id;
641 mark_implicit_builtin(StorageClassInput, BuiltInGlobalInvocationId, var_id);
642 }
643 else if (need_tesc_params && !has_invocation_id)
Chip Daviseb89c3a2019-02-03 23:58:46 -0600644 {
645 uint32_t var_id = ir.increase_bound_by(1);
646
647 // Create gl_InvocationID.
648 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
649 set_decoration(var_id, DecorationBuiltIn, BuiltInInvocationId);
650 builtin_invocation_id_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200651 mark_implicit_builtin(StorageClassInput, BuiltInInvocationId, var_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -0600652 }
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200653
Chip Davis688c5fc2020-02-20 21:38:28 -0600654 if (need_tesc_params && !has_primitive_id)
Chip Daviseb89c3a2019-02-03 23:58:46 -0600655 {
656 uint32_t var_id = ir.increase_bound_by(1);
657
658 // Create gl_PrimitiveID.
659 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
660 set_decoration(var_id, DecorationBuiltIn, BuiltInPrimitiveId);
661 builtin_primitive_id_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200662 mark_implicit_builtin(StorageClassInput, BuiltInPrimitiveId, var_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -0600663 }
Chip Davis688c5fc2020-02-20 21:38:28 -0600664
665 if (need_grid_params)
666 {
667 uint32_t var_id = ir.increase_bound_by(1);
668
669 set<SPIRVariable>(var_id, build_extended_vector_type(get_uint_type_id(), 3), StorageClassInput);
670 set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize);
671 get_entry_point().interface_variables.push_back(var_id);
672 set_name(var_id, "spvStageInputSize");
673 builtin_stage_input_size_id = var_id;
674 }
Chip Daviseb89c3a2019-02-03 23:58:46 -0600675 }
Chip Davis9d941572019-05-15 16:03:30 -0500676
677 if (!has_subgroup_invocation_id && (need_subgroup_mask || needs_subgroup_invocation_id))
678 {
Chip Davis884bc6d2020-07-22 15:25:10 -0600679 uint32_t offset = ir.increase_bound_by(2);
680 uint32_t type_ptr_id = offset;
681 uint32_t var_id = offset + 1;
Chip Davis9d941572019-05-15 16:03:30 -0500682
683 // Create gl_SubgroupInvocationID.
Chip Davis9d941572019-05-15 16:03:30 -0500684 SPIRType uint_type_ptr;
Chip Davis884bc6d2020-07-22 15:25:10 -0600685 uint_type_ptr = get_uint_type();
Chip Davis9d941572019-05-15 16:03:30 -0500686 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100687 uint_type_ptr.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600688 uint_type_ptr.parent_type = get_uint_type_id();
Chip Davis9d941572019-05-15 16:03:30 -0500689 uint_type_ptr.storage = StorageClassInput;
690 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
Chip Davis884bc6d2020-07-22 15:25:10 -0600691 ptr_type.self = get_uint_type_id();
Chip Davis9d941572019-05-15 16:03:30 -0500692
693 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
694 set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupLocalInvocationId);
695 builtin_subgroup_invocation_id_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200696 mark_implicit_builtin(StorageClassInput, BuiltInSubgroupLocalInvocationId, var_id);
Chip Davis9d941572019-05-15 16:03:30 -0500697 }
698
Chip Davis065b5bd2020-10-20 23:59:30 -0500699 if (!has_subgroup_size && (need_subgroup_ge_mask || needs_subgroup_size))
Chip Davis9d941572019-05-15 16:03:30 -0500700 {
Chip Davis884bc6d2020-07-22 15:25:10 -0600701 uint32_t offset = ir.increase_bound_by(2);
702 uint32_t type_ptr_id = offset;
703 uint32_t var_id = offset + 1;
Chip Davis9d941572019-05-15 16:03:30 -0500704
705 // Create gl_SubgroupSize.
Chip Davis9d941572019-05-15 16:03:30 -0500706 SPIRType uint_type_ptr;
Chip Davis884bc6d2020-07-22 15:25:10 -0600707 uint_type_ptr = get_uint_type();
Chip Davis9d941572019-05-15 16:03:30 -0500708 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100709 uint_type_ptr.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -0600710 uint_type_ptr.parent_type = get_uint_type_id();
Chip Davis9d941572019-05-15 16:03:30 -0500711 uint_type_ptr.storage = StorageClassInput;
712 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
Chip Davis884bc6d2020-07-22 15:25:10 -0600713 ptr_type.self = get_uint_type_id();
Chip Davis9d941572019-05-15 16:03:30 -0500714
715 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
716 set_decoration(var_id, DecorationBuiltIn, BuiltInSubgroupSize);
717 builtin_subgroup_size_id = var_id;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200718 mark_implicit_builtin(StorageClassInput, BuiltInSubgroupSize, var_id);
Chip Davis9d941572019-05-15 16:03:30 -0500719 }
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500720
Chip Davis688c5fc2020-02-20 21:38:28 -0600721 if (need_dispatch_base || need_vertex_base_params)
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500722 {
Chip Davis688c5fc2020-02-20 21:38:28 -0600723 if (workgroup_id_type == 0)
724 workgroup_id_type = build_extended_vector_type(get_uint_type_id(), 3);
Chip Davisfb5ee4c2019-07-22 13:08:04 -0500725 uint32_t var_id;
726 if (msl_options.supports_msl_version(1, 2))
727 {
728 // If we have MSL 1.2, we can (ab)use the [[grid_origin]] builtin
729 // to convey this information and save a buffer slot.
730 uint32_t offset = ir.increase_bound_by(1);
731 var_id = offset;
732
733 set<SPIRVariable>(var_id, workgroup_id_type, StorageClassInput);
734 set_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase);
735 get_entry_point().interface_variables.push_back(var_id);
736 }
737 else
738 {
739 // Otherwise, we need to fall back to a good ol' fashioned buffer.
740 uint32_t offset = ir.increase_bound_by(2);
741 var_id = offset;
742 uint32_t type_id = offset + 1;
743
744 SPIRType var_type = get<SPIRType>(workgroup_id_type);
745 var_type.storage = StorageClassUniform;
746 set<SPIRType>(type_id, var_type);
747
748 set<SPIRVariable>(var_id, type_id, StorageClassUniform);
749 // This should never match anything.
750 set_decoration(var_id, DecorationDescriptorSet, ~(5u));
751 set_decoration(var_id, DecorationBinding, msl_options.indirect_params_buffer_index);
752 set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary,
753 msl_options.indirect_params_buffer_index);
754 }
755 set_name(var_id, "spvDispatchBase");
756 builtin_dispatch_base_id = var_id;
757 }
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200758
Bill Hollingsebb50982021-07-13 21:22:13 -0400759 if (has_additional_fixed_sample_mask() && !does_shader_write_sample_mask)
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200760 {
761 uint32_t offset = ir.increase_bound_by(2);
762 uint32_t var_id = offset + 1;
763
764 // Create gl_SampleMask.
765 SPIRType uint_type_ptr_out;
766 uint_type_ptr_out = get_uint_type();
767 uint_type_ptr_out.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100768 uint_type_ptr_out.pointer_depth++;
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200769 uint_type_ptr_out.parent_type = get_uint_type_id();
770 uint_type_ptr_out.storage = StorageClassOutput;
Hans-Kristian Arntzena0744152020-08-21 16:14:13 +0200771
Tomek Ponitka18f23c42020-07-22 18:37:17 +0200772 auto &ptr_out_type = set<SPIRType>(offset, uint_type_ptr_out);
773 ptr_out_type.self = get_uint_type_id();
774 set<SPIRVariable>(var_id, offset, StorageClassOutput);
775 set_decoration(var_id, DecorationBuiltIn, BuiltInSampleMask);
776 builtin_sample_mask_id = var_id;
777 mark_implicit_builtin(StorageClassOutput, BuiltInSampleMask, var_id);
778 }
Chip Davis68908352020-11-18 23:16:46 -0600779
780 if (need_local_invocation_index && !has_local_invocation_index)
781 {
782 uint32_t offset = ir.increase_bound_by(2);
783 uint32_t type_ptr_id = offset;
784 uint32_t var_id = offset + 1;
785
786 // Create gl_LocalInvocationIndex.
787 SPIRType uint_type_ptr;
788 uint_type_ptr = get_uint_type();
789 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100790 uint_type_ptr.pointer_depth++;
Chip Davis68908352020-11-18 23:16:46 -0600791 uint_type_ptr.parent_type = get_uint_type_id();
792 uint_type_ptr.storage = StorageClassInput;
793
794 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
795 ptr_type.self = get_uint_type_id();
796 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
797 set_decoration(var_id, DecorationBuiltIn, BuiltInLocalInvocationIndex);
798 builtin_local_invocation_index_id = var_id;
799 mark_implicit_builtin(StorageClassInput, BuiltInLocalInvocationIndex, var_id);
800 }
801
802 if (need_workgroup_size && !has_workgroup_size)
803 {
804 uint32_t offset = ir.increase_bound_by(2);
805 uint32_t type_ptr_id = offset;
806 uint32_t var_id = offset + 1;
807
808 // Create gl_WorkgroupSize.
809 uint32_t type_id = build_extended_vector_type(get_uint_type_id(), 3);
810 SPIRType uint_type_ptr = get<SPIRType>(type_id);
811 uint_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100812 uint_type_ptr.pointer_depth++;
Chip Davis68908352020-11-18 23:16:46 -0600813 uint_type_ptr.parent_type = type_id;
814 uint_type_ptr.storage = StorageClassInput;
815
816 auto &ptr_type = set<SPIRType>(type_ptr_id, uint_type_ptr);
817 ptr_type.self = type_id;
818 set<SPIRVariable>(var_id, type_ptr_id, StorageClassInput);
819 set_decoration(var_id, DecorationBuiltIn, BuiltInWorkgroupSize);
820 builtin_workgroup_size_id = var_id;
821 mark_implicit_builtin(StorageClassInput, BuiltInWorkgroupSize, var_id);
822 }
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +0100823 }
Chip Davis4302c5a2018-09-22 19:36:11 -0500824
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +0200825 if (needs_swizzle_buffer_def)
Chip Davis4302c5a2018-09-22 19:36:11 -0500826 {
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200827 uint32_t var_id = build_constant_uint_array_pointer();
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +0200828 set_name(var_id, "spvSwizzleConstants");
Chip Davis4302c5a2018-09-22 19:36:11 -0500829 // This should never match anything.
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200830 set_decoration(var_id, DecorationDescriptorSet, kSwizzleBufferBinding);
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +0200831 set_decoration(var_id, DecorationBinding, msl_options.swizzle_buffer_index);
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +0200832 set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.swizzle_buffer_index);
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +0200833 swizzle_buffer_id = var_id;
Chip Davis4302c5a2018-09-22 19:36:11 -0500834 }
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200835
836 if (!buffers_requiring_array_length.empty())
837 {
838 uint32_t var_id = build_constant_uint_array_pointer();
839 set_name(var_id, "spvBufferSizeConstants");
840 // This should never match anything.
841 set_decoration(var_id, DecorationDescriptorSet, kBufferSizeBufferBinding);
842 set_decoration(var_id, DecorationBinding, msl_options.buffer_size_buffer_index);
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +0200843 set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.buffer_size_buffer_index);
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200844 buffer_size_buffer_id = var_id;
845 }
Chip Davis7eecf5a2019-05-31 12:06:20 -0500846
847 if (needs_view_mask_buffer())
848 {
849 uint32_t var_id = build_constant_uint_array_pointer();
850 set_name(var_id, "spvViewMask");
851 // This should never match anything.
852 set_decoration(var_id, DecorationDescriptorSet, ~(4u));
853 set_decoration(var_id, DecorationBinding, msl_options.view_mask_buffer_index);
854 set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary, msl_options.view_mask_buffer_index);
855 view_mask_buffer_id = var_id;
856 }
Chip Daviscb359342019-09-05 23:14:12 -0500857
858 if (!buffers_requiring_dynamic_offset.empty())
859 {
860 uint32_t var_id = build_constant_uint_array_pointer();
861 set_name(var_id, "spvDynamicOffsets");
862 // This should never match anything.
863 set_decoration(var_id, DecorationDescriptorSet, ~(5u));
864 set_decoration(var_id, DecorationBinding, msl_options.dynamic_offsets_buffer_index);
865 set_extended_decoration(var_id, SPIRVCrossDecorationResourceIndexPrimary,
866 msl_options.dynamic_offsets_buffer_index);
867 dynamic_offsets_buffer_id = var_id;
868 }
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100869
870 // If we're returning a struct from a vertex-like entry point, we must return a position attribute.
871 bool need_position =
872 (get_execution_model() == ExecutionModelVertex ||
873 get_execution_model() == ExecutionModelTessellationEvaluation) &&
874 !capture_output_to_buffer && !get_is_rasterization_disabled() &&
875 !active_output_builtins.get(BuiltInPosition);
876
877 if (need_position)
878 {
879 // If we can get away with returning void from entry point, we don't need to care.
Bill Hollings3105e822021-08-16 11:23:15 -0400880 // If there is at least one other stage output, we need to return [[position]],
881 // so we need to create one if it doesn't appear in the SPIR-V. Before adding the
882 // implicit variable, check if it actually exists already, but just has not been used
883 // or initialized, and if so, mark it as active, and do not create the implicit variable.
884 bool has_output = false;
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100885 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
886 if (var.storage == StorageClassOutput && interface_variable_exists_in_entry_point(var.self))
Bill Hollings3105e822021-08-16 11:23:15 -0400887 {
888 has_output = true;
889
890 // Check if the var is the Position builtin
891 if (has_decoration(var.self, DecorationBuiltIn) && get_decoration(var.self, DecorationBuiltIn) == BuiltInPosition)
892 active_output_builtins.set(BuiltInPosition);
893
894 // If the var is a struct, check if any members is the Position builtin
895 auto &var_type = get_variable_element_type(var);
896 if (var_type.basetype == SPIRType::Struct)
897 {
898 auto mbr_cnt = var_type.member_types.size();
899 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
900 {
901 auto builtin = BuiltInMax;
902 bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
903 if (is_builtin && builtin == BuiltInPosition)
904 active_output_builtins.set(BuiltInPosition);
905 }
906 }
907 }
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100908 });
Bill Hollings3105e822021-08-16 11:23:15 -0400909 need_position = has_output && !active_output_builtins.get(BuiltInPosition);
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100910 }
911
912 if (need_position)
913 {
914 uint32_t offset = ir.increase_bound_by(3);
915 uint32_t type_id = offset;
916 uint32_t type_ptr_id = offset + 1;
917 uint32_t var_id = offset + 2;
918
919 // Create gl_Position.
920 SPIRType vec4_type;
921 vec4_type.basetype = SPIRType::Float;
922 vec4_type.width = 32;
923 vec4_type.vecsize = 4;
924 set<SPIRType>(type_id, vec4_type);
925
926 SPIRType vec4_type_ptr;
927 vec4_type_ptr = vec4_type;
928 vec4_type_ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +0100929 vec4_type_ptr.pointer_depth++;
Hans-Kristian Arntzen0ad12a02021-02-15 12:49:37 +0100930 vec4_type_ptr.parent_type = type_id;
931 vec4_type_ptr.storage = StorageClassOutput;
932 auto &ptr_type = set<SPIRType>(type_ptr_id, vec4_type_ptr);
933 ptr_type.self = type_id;
934
935 set<SPIRVariable>(var_id, type_ptr_id, StorageClassOutput);
936 set_decoration(var_id, DecorationBuiltIn, BuiltInPosition);
937 mark_implicit_builtin(StorageClassOutput, BuiltInPosition, var_id);
938 }
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200939}
940
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400941// Checks if the specified builtin variable (e.g. gl_InstanceIndex) is marked as active.
942// If not, it marks it as active and forces a recompilation.
943// This might be used when the optimization of inactive builtins was too optimistic (e.g. when "spvOut" is emitted).
944void CompilerMSL::ensure_builtin(spv::StorageClass storage, spv::BuiltIn builtin)
945{
946 Bitset *active_builtins = nullptr;
947 switch (storage)
948 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -0400949 case StorageClassInput:
950 active_builtins = &active_input_builtins;
951 break;
952
953 case StorageClassOutput:
954 active_builtins = &active_output_builtins;
955 break;
956
957 default:
958 break;
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400959 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -0400960
Lukas Hermanns9f9276f2019-09-19 14:44:30 -0400961 // At this point, the specified builtin variable must have already been declared in the entry point.
962 // If not, mark as active and force recompile.
963 if (active_builtins != nullptr && !active_builtins->get(builtin))
964 {
965 active_builtins->set(builtin);
966 force_recompile();
967 }
968}
969
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200970void CompilerMSL::mark_implicit_builtin(StorageClass storage, BuiltIn builtin, uint32_t id)
971{
972 Bitset *active_builtins = nullptr;
973 switch (storage)
974 {
975 case StorageClassInput:
976 active_builtins = &active_input_builtins;
977 break;
978
979 case StorageClassOutput:
980 active_builtins = &active_output_builtins;
981 break;
982
983 default:
984 break;
985 }
986
987 assert(active_builtins != nullptr);
988 active_builtins->set(builtin);
Hans-Kristian Arntzend9d33592020-04-03 12:50:21 +0200989
990 auto &var = get_entry_point().interface_variables;
991 if (find(begin(var), end(var), VariableID(id)) == end(var))
992 var.push_back(id);
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +0200993}
994
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +0200995uint32_t CompilerMSL::build_constant_uint_array_pointer()
996{
Chip Davis884bc6d2020-07-22 15:25:10 -0600997 uint32_t offset = ir.increase_bound_by(3);
998 uint32_t type_ptr_id = offset;
999 uint32_t type_ptr_ptr_id = offset + 1;
1000 uint32_t var_id = offset + 2;
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02001001
1002 // Create a buffer to hold extra data, including the swizzle constants.
Chip Davis884bc6d2020-07-22 15:25:10 -06001003 SPIRType uint_type_pointer = get_uint_type();
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02001004 uint_type_pointer.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01001005 uint_type_pointer.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -06001006 uint_type_pointer.parent_type = get_uint_type_id();
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02001007 uint_type_pointer.storage = StorageClassUniform;
1008 set<SPIRType>(type_ptr_id, uint_type_pointer);
1009 set_decoration(type_ptr_id, DecorationArrayStride, 4);
1010
1011 SPIRType uint_type_pointer2 = uint_type_pointer;
1012 uint_type_pointer2.pointer_depth++;
1013 uint_type_pointer2.parent_type = type_ptr_id;
1014 set<SPIRType>(type_ptr_ptr_id, uint_type_pointer2);
1015
1016 set<SPIRVariable>(var_id, type_ptr_ptr_id, StorageClassUniformConstant);
1017 return var_id;
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01001018}
1019
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001020static string create_sampler_address(const char *prefix, MSLSamplerAddress addr)
1021{
1022 switch (addr)
1023 {
1024 case MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE:
1025 return join(prefix, "address::clamp_to_edge");
1026 case MSL_SAMPLER_ADDRESS_CLAMP_TO_ZERO:
1027 return join(prefix, "address::clamp_to_zero");
1028 case MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER:
1029 return join(prefix, "address::clamp_to_border");
1030 case MSL_SAMPLER_ADDRESS_REPEAT:
1031 return join(prefix, "address::repeat");
1032 case MSL_SAMPLER_ADDRESS_MIRRORED_REPEAT:
1033 return join(prefix, "address::mirrored_repeat");
1034 default:
1035 SPIRV_CROSS_THROW("Invalid sampler addressing mode.");
1036 }
1037}
1038
Chip Daviseb89c3a2019-02-03 23:58:46 -06001039SPIRType &CompilerMSL::get_stage_in_struct_type()
1040{
1041 auto &si_var = get<SPIRVariable>(stage_in_var_id);
1042 return get_variable_data_type(si_var);
1043}
1044
Chip Davisc51e5b72019-01-08 16:33:32 -06001045SPIRType &CompilerMSL::get_stage_out_struct_type()
1046{
1047 auto &so_var = get<SPIRVariable>(stage_out_var_id);
1048 return get_variable_data_type(so_var);
1049}
1050
Chip Davise75add42019-02-05 18:13:26 -06001051SPIRType &CompilerMSL::get_patch_stage_in_struct_type()
1052{
1053 auto &si_var = get<SPIRVariable>(patch_stage_in_var_id);
1054 return get_variable_data_type(si_var);
1055}
1056
Chip Daviseb89c3a2019-02-03 23:58:46 -06001057SPIRType &CompilerMSL::get_patch_stage_out_struct_type()
1058{
1059 auto &so_var = get<SPIRVariable>(patch_stage_out_var_id);
1060 return get_variable_data_type(so_var);
1061}
1062
1063std::string CompilerMSL::get_tess_factor_struct_name()
1064{
1065 if (get_entry_point().flags.get(ExecutionModeTriangles))
1066 return "MTLTriangleTessellationFactorsHalf";
1067 return "MTLQuadTessellationFactorsHalf";
1068}
1069
Chip Davis884bc6d2020-07-22 15:25:10 -06001070SPIRType &CompilerMSL::get_uint_type()
1071{
1072 return get<SPIRType>(get_uint_type_id());
1073}
1074
1075uint32_t CompilerMSL::get_uint_type_id()
1076{
1077 if (uint_type_id != 0)
1078 return uint_type_id;
1079
1080 uint_type_id = ir.increase_bound_by(1);
1081
1082 SPIRType type;
1083 type.basetype = SPIRType::UInt;
1084 type.width = 32;
1085 set<SPIRType>(uint_type_id, type);
1086 return uint_type_id;
1087}
1088
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001089void CompilerMSL::emit_entry_point_declarations()
1090{
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001091 // FIXME: Get test coverage here ...
Lukas Hermanns50ac6862019-09-18 14:03:54 -04001092 // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04001093 declare_complex_constant_arrays();
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001094
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001095 // Emit constexpr samplers here.
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +02001096 for (auto &samp : constexpr_samplers_by_id)
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001097 {
1098 auto &var = get<SPIRVariable>(samp.first);
1099 auto &type = get<SPIRType>(var.basetype);
1100 if (type.basetype == SPIRType::Sampler)
1101 add_resource_name(samp.first);
1102
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001103 SmallVector<string> args;
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001104 auto &s = samp.second;
1105
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001106 if (s.coord != MSL_SAMPLER_COORD_NORMALIZED)
1107 args.push_back("coord::pixel");
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001108
1109 if (s.min_filter == s.mag_filter)
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001110 {
1111 if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST)
1112 args.push_back("filter::linear");
1113 }
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001114 else
1115 {
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001116 if (s.min_filter != MSL_SAMPLER_FILTER_NEAREST)
1117 args.push_back("min_filter::linear");
1118 if (s.mag_filter != MSL_SAMPLER_FILTER_NEAREST)
1119 args.push_back("mag_filter::linear");
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001120 }
1121
1122 switch (s.mip_filter)
1123 {
1124 case MSL_SAMPLER_MIP_FILTER_NONE:
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001125 // Default
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001126 break;
1127 case MSL_SAMPLER_MIP_FILTER_NEAREST:
1128 args.push_back("mip_filter::nearest");
1129 break;
1130 case MSL_SAMPLER_MIP_FILTER_LINEAR:
1131 args.push_back("mip_filter::linear");
1132 break;
1133 default:
1134 SPIRV_CROSS_THROW("Invalid mip filter.");
1135 }
1136
1137 if (s.s_address == s.t_address && s.s_address == s.r_address)
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001138 {
1139 if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
1140 args.push_back(create_sampler_address("", s.s_address));
1141 }
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001142 else
1143 {
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001144 if (s.s_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
1145 args.push_back(create_sampler_address("s_", s.s_address));
1146 if (s.t_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
1147 args.push_back(create_sampler_address("t_", s.t_address));
1148 if (s.r_address != MSL_SAMPLER_ADDRESS_CLAMP_TO_EDGE)
1149 args.push_back(create_sampler_address("r_", s.r_address));
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001150 }
1151
1152 if (s.compare_enable)
1153 {
1154 switch (s.compare_func)
1155 {
Hans-Kristian Arntzene30a9422018-04-18 16:19:55 +02001156 case MSL_SAMPLER_COMPARE_FUNC_ALWAYS:
1157 args.push_back("compare_func::always");
1158 break;
1159 case MSL_SAMPLER_COMPARE_FUNC_NEVER:
1160 args.push_back("compare_func::never");
1161 break;
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001162 case MSL_SAMPLER_COMPARE_FUNC_EQUAL:
1163 args.push_back("compare_func::equal");
1164 break;
1165 case MSL_SAMPLER_COMPARE_FUNC_NOT_EQUAL:
1166 args.push_back("compare_func::not_equal");
1167 break;
1168 case MSL_SAMPLER_COMPARE_FUNC_LESS:
1169 args.push_back("compare_func::less");
1170 break;
1171 case MSL_SAMPLER_COMPARE_FUNC_LESS_EQUAL:
1172 args.push_back("compare_func::less_equal");
1173 break;
1174 case MSL_SAMPLER_COMPARE_FUNC_GREATER:
1175 args.push_back("compare_func::greater");
1176 break;
1177 case MSL_SAMPLER_COMPARE_FUNC_GREATER_EQUAL:
1178 args.push_back("compare_func::greater_equal");
1179 break;
1180 default:
1181 SPIRV_CROSS_THROW("Invalid sampler compare function.");
1182 }
1183 }
1184
1185 if (s.s_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER || s.t_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER ||
1186 s.r_address == MSL_SAMPLER_ADDRESS_CLAMP_TO_BORDER)
1187 {
1188 switch (s.border_color)
1189 {
1190 case MSL_SAMPLER_BORDER_COLOR_OPAQUE_BLACK:
1191 args.push_back("border_color::opaque_black");
1192 break;
1193 case MSL_SAMPLER_BORDER_COLOR_OPAQUE_WHITE:
1194 args.push_back("border_color::opaque_white");
1195 break;
1196 case MSL_SAMPLER_BORDER_COLOR_TRANSPARENT_BLACK:
1197 args.push_back("border_color::transparent_black");
1198 break;
1199 default:
1200 SPIRV_CROSS_THROW("Invalid sampler border color.");
1201 }
1202 }
1203
1204 if (s.anisotropy_enable)
1205 args.push_back(join("max_anisotropy(", s.max_anisotropy, ")"));
1206 if (s.lod_clamp_enable)
Hans-Kristian Arntzene351e5c2018-04-18 16:31:08 +02001207 {
Hans-Kristian Arntzen825ff4a2019-02-28 11:26:26 +01001208 args.push_back(join("lod_clamp(", convert_to_string(s.lod_clamp_min, current_locale_radix_character), ", ",
1209 convert_to_string(s.lod_clamp_max, current_locale_radix_character), ")"));
Hans-Kristian Arntzene351e5c2018-04-18 16:31:08 +02001210 }
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001211
Chip Davis39dce882019-08-02 15:11:19 -05001212 // If we would emit no arguments, then omit the parentheses entirely. Otherwise,
1213 // we'll wind up with a "most vexing parse" situation.
1214 if (args.empty())
1215 statement("constexpr sampler ",
1216 type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first),
1217 ";");
1218 else
1219 statement("constexpr sampler ",
1220 type.basetype == SPIRType::SampledImage ? to_sampler_expression(samp.first) : to_name(samp.first),
1221 "(", merge(args), ");");
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001222 }
Chip Davis3a9af962018-09-26 20:06:05 -05001223
Chip Daviscb359342019-09-05 23:14:12 -05001224 // Emit dynamic buffers here.
Hans-Kristian Arntzen1935f1a2019-09-06 10:11:18 +02001225 for (auto &dynamic_buffer : buffers_requiring_dynamic_offset)
Chip Daviscb359342019-09-05 23:14:12 -05001226 {
Hans-Kristian Arntzen1935f1a2019-09-06 10:11:18 +02001227 if (!dynamic_buffer.second.second)
1228 {
1229 // Could happen if no buffer was used at requested binding point.
1230 continue;
1231 }
1232
1233 const auto &var = get<SPIRVariable>(dynamic_buffer.second.second);
Chip Daviscb359342019-09-05 23:14:12 -05001234 uint32_t var_id = var.self;
1235 const auto &type = get_variable_data_type(var);
1236 string name = to_name(var.self);
1237 uint32_t desc_set = get_decoration(var.self, DecorationDescriptorSet);
1238 uint32_t arg_id = argument_buffer_ids[desc_set];
Hans-Kristian Arntzen1935f1a2019-09-06 10:11:18 +02001239 uint32_t base_index = dynamic_buffer.second.first;
Chip Daviscb359342019-09-05 23:14:12 -05001240
1241 if (!type.array.empty())
1242 {
1243 // This is complicated, because we need to support arrays of arrays.
1244 // And it's even worse if the outermost dimension is a runtime array, because now
1245 // all this complicated goop has to go into the shader itself. (FIXME)
1246 if (!type.array[type.array.size() - 1])
1247 SPIRV_CROSS_THROW("Runtime arrays with dynamic offsets are not supported yet.");
1248 else
1249 {
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +01001250 is_using_builtin_array = true;
Chip Daviscb359342019-09-05 23:14:12 -05001251 statement(get_argument_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id), name,
1252 type_to_array_glsl(type), " =");
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +02001253
Chip Daviscb359342019-09-05 23:14:12 -05001254 uint32_t dim = uint32_t(type.array.size());
1255 uint32_t j = 0;
1256 for (SmallVector<uint32_t> indices(type.array.size());
1257 indices[type.array.size() - 1] < to_array_size_literal(type); j++)
1258 {
1259 while (dim > 0)
1260 {
1261 begin_scope();
1262 --dim;
1263 }
1264
1265 string arrays;
1266 for (uint32_t i = uint32_t(type.array.size()); i; --i)
1267 arrays += join("[", indices[i - 1], "]");
Hans-Kristian Arntzen2082e7e2019-09-06 14:23:16 +02001268 statement("(", get_argument_address_space(var), " ", type_to_glsl(type), "* ",
1269 to_restrict(var_id, false), ")((", get_argument_address_space(var), " char* ",
1270 to_restrict(var_id, false), ")", to_name(arg_id), ".", ensure_valid_name(name, "m"),
1271 arrays, " + ", to_name(dynamic_offsets_buffer_id), "[", base_index + j, "]),");
Chip Daviscb359342019-09-05 23:14:12 -05001272
1273 while (++indices[dim] >= to_array_size_literal(type, dim) && dim < type.array.size() - 1)
1274 {
1275 end_scope(",");
1276 indices[dim++] = 0;
1277 }
1278 }
1279 end_scope_decl();
1280 statement_no_indent("");
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +01001281 is_using_builtin_array = false;
Chip Daviscb359342019-09-05 23:14:12 -05001282 }
1283 }
1284 else
1285 {
1286 statement(get_argument_address_space(var), " auto& ", to_restrict(var_id), name, " = *(",
1287 get_argument_address_space(var), " ", type_to_glsl(type), "* ", to_restrict(var_id, false), ")((",
1288 get_argument_address_space(var), " char* ", to_restrict(var_id, false), ")", to_name(arg_id), ".",
1289 ensure_valid_name(name, "m"), " + ", to_name(dynamic_offsets_buffer_id), "[", base_index, "]);");
1290 }
1291 }
1292
Chip Davis3a9af962018-09-26 20:06:05 -05001293 // Emit buffer arrays here.
1294 for (uint32_t array_id : buffer_arrays)
1295 {
1296 const auto &var = get<SPIRVariable>(array_id);
Chip Davis3bfb2f92018-12-03 02:06:33 -06001297 const auto &type = get_variable_data_type(var);
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +02001298 const auto &buffer_type = get_variable_element_type(var);
Hans-Kristian Arntzenee395af2019-02-25 11:09:00 +01001299 string name = to_name(array_id);
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01001300 statement(get_argument_address_space(var), " ", type_to_glsl(buffer_type), "* ", to_restrict(array_id), name,
1301 "[] =");
Chip Davis3a9af962018-09-26 20:06:05 -05001302 begin_scope();
Chip Daviscb359342019-09-05 23:14:12 -05001303 for (uint32_t i = 0; i < to_array_size_literal(type); ++i)
1304 statement(name, "_", i, ",");
Chip Davis3a9af962018-09-26 20:06:05 -05001305 end_scope_decl();
Hans-Kristian Arntzen4e7777c2019-01-30 13:31:17 +01001306 statement_no_indent("");
Chip Davis3a9af962018-09-26 20:06:05 -05001307 }
Chip Davisb7433c02018-09-27 11:01:46 -05001308 // For some reason, without this, we end up emitting the arrays twice.
Chip Davis3a9af962018-09-26 20:06:05 -05001309 buffer_arrays.clear();
Chip Davisb29f83c2020-04-10 01:13:33 -05001310
1311 // Emit disabled fragment outputs.
1312 std::sort(disabled_frag_outputs.begin(), disabled_frag_outputs.end());
1313 for (uint32_t var_id : disabled_frag_outputs)
1314 {
1315 auto &var = get<SPIRVariable>(var_id);
1316 add_local_variable_name(var_id);
1317 statement(variable_decl(var), ";");
1318 var.deferred_declaration = false;
1319 }
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +02001320}
1321
Bill Hollings5550c872017-03-12 17:42:51 -04001322string CompilerMSL::compile()
Bill Hollings103aabf2016-04-06 17:42:27 -04001323{
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +01001324 replace_illegal_entry_point_names();
Hans-Kristian Arntzena0744152020-08-21 16:14:13 +02001325 ir.fixup_reserved_names();
1326
Bill Hollings5ee6b462018-01-05 23:22:36 -05001327 // Do not deal with GLES-isms like precision, older extensions and such.
Hans-Kristian Arntzena803e5a2018-03-09 15:25:25 +01001328 options.vulkan_semantics = true;
1329 options.es = false;
1330 options.version = 450;
Chip Davis3bfb2f92018-12-03 02:06:33 -06001331 backend.null_pointer_literal = "nullptr";
Bill Hollings5ee6b462018-01-05 23:22:36 -05001332 backend.float_literal_suffix = false;
1333 backend.uint32_t_literal_suffix = true;
Bill Hollingsc48702d2019-03-28 14:23:32 -04001334 backend.int16_t_literal_suffix = "";
Hans-Kristian Arntzen3c112542019-09-19 10:19:51 +02001335 backend.uint16_t_literal_suffix = "";
Bill Hollings5ee6b462018-01-05 23:22:36 -05001336 backend.basic_int_type = "int";
1337 backend.basic_uint_type = "uint";
Chip Davis1fb27b42018-10-31 09:43:03 -05001338 backend.basic_int8_type = "char";
1339 backend.basic_uint8_type = "uchar";
1340 backend.basic_int16_type = "short";
1341 backend.basic_uint16_type = "ushort";
Bill Hollings5ee6b462018-01-05 23:22:36 -05001342 backend.discard_literal = "discard_fragment()";
Chip Davis2219c4a2020-09-28 23:07:55 -05001343 backend.demote_literal = "discard_fragment()";
Chip Davis6628ea62019-07-10 23:46:40 -05001344 backend.boolean_mix_function = "select";
Bill Hollings5ee6b462018-01-05 23:22:36 -05001345 backend.swizzle_is_function = false;
1346 backend.shared_is_implied = false;
Bill Hollingsba1e4152018-01-12 17:19:24 -05001347 backend.use_initializer_list = true;
Hans-Kristian Arntzen06041982018-01-23 16:36:20 +01001348 backend.use_typed_initializer_list = true;
Bill Hollings5ee6b462018-01-05 23:22:36 -05001349 backend.native_row_major_matrix = false;
Hans-Kristian Arntzen647ddae2019-05-13 14:58:27 +02001350 backend.unsized_array_supported = false;
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01001351 backend.can_declare_arrays_inline = false;
Bill Hollings2964e322018-02-13 14:44:40 -05001352 backend.allow_truncated_access_chain = true;
Hans-Kristian Arntzena4ac2752019-02-22 12:02:11 +01001353 backend.comparison_image_samples_scalar = true;
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +02001354 backend.native_pointers = true;
Hans-Kristian Arntzen647ddae2019-05-13 14:58:27 +02001355 backend.nonuniform_qualifier = "";
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02001356 backend.support_small_type_sampling_result = true;
Hans-Kristian Arntzen3b5c4c72019-10-24 17:05:55 +02001357 backend.supports_empty_struct = true;
Sebastián Aedo6d8302e2021-11-18 16:08:59 -03001358 backend.support_64bit_switch = true;
Bill Hollings5ee6b462018-01-05 23:22:36 -05001359
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +01001360 // Allow Metal to use the array<T> template unless we force it off.
1361 backend.can_return_array = !msl_options.force_native_arrays;
1362 backend.array_is_value_type = !msl_options.force_native_arrays;
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02001363 // Arrays which are part of buffer objects are never considered to be native arrays.
1364 backend.buffer_offset_array_is_value_type = false;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01001365 backend.support_pointer_to_pointer = true;
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +01001366
Chip Davisc51e5b72019-01-08 16:33:32 -06001367 capture_output_to_buffer = msl_options.capture_output_to_buffer;
1368 is_rasterization_disabled = msl_options.disable_rasterization || capture_output_to_buffer;
Bill Hollings0d6202e2018-07-26 16:40:32 -04001369
Hans-Kristian Arntzen909040e2019-07-09 15:31:01 +02001370 // Initialize array here rather than constructor, MSVC 2013 workaround.
1371 for (auto &id : next_metal_resource_ids)
1372 id = 0;
1373
Hans-Kristian Arntzen96492642019-05-23 14:54:04 +02001374 fixup_type_alias();
Bill Hollings1c180782017-11-05 21:34:42 -05001375 replace_illegal_names();
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +01001376 sync_entry_point_aliases_and_names();
Bill Hollings1c180782017-11-05 21:34:42 -05001377
Hans-Kristian Arntzenb5ed7062018-07-05 10:42:05 +02001378 build_function_control_flow_graphs_and_analyze();
Hans-Kristian Arntzen099f3072017-03-06 15:21:00 +01001379 update_active_builtins();
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01001380 analyze_image_and_sampler_usage();
Chip Davisc11374c2018-09-24 12:10:27 -05001381 analyze_sampled_image_usage();
Hans-Kristian Arntzen261b4692019-09-04 12:18:04 +02001382 analyze_interlocked_resource_usage();
Chip Davis9d941572019-05-15 16:03:30 -05001383 preprocess_op_codes();
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01001384 build_implicit_builtins();
1385
Bill Hollingsb41e1482017-05-29 20:45:05 -04001386 fixup_image_load_store_access();
Hans-Kristian Arntzen099f3072017-03-06 15:21:00 +01001387
Bill Hollingsf591bc02017-06-30 19:10:46 -04001388 set_enabled_interface_variables(get_active_interface_variables());
Hans-Kristian Arntzenc3bd1362020-01-16 11:07:30 +01001389 if (msl_options.force_active_argument_buffer_resources)
1390 activate_argument_buffer_resources();
1391
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +02001392 if (swizzle_buffer_id)
1393 active_interface_variables.insert(swizzle_buffer_id);
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02001394 if (buffer_size_buffer_id)
1395 active_interface_variables.insert(buffer_size_buffer_id);
Chip Davis7eecf5a2019-05-31 12:06:20 -05001396 if (view_mask_buffer_id)
1397 active_interface_variables.insert(view_mask_buffer_id);
Chip Daviscb359342019-09-05 23:14:12 -05001398 if (dynamic_offsets_buffer_id)
1399 active_interface_variables.insert(dynamic_offsets_buffer_id);
Chip Davis7eecf5a2019-05-31 12:06:20 -05001400 if (builtin_layer_id)
1401 active_interface_variables.insert(builtin_layer_id);
Chip Davisfb5ee4c2019-07-22 13:08:04 -05001402 if (builtin_dispatch_base_id && !msl_options.supports_msl_version(1, 2))
1403 active_interface_variables.insert(builtin_dispatch_base_id);
Tomek Ponitka18f23c42020-07-22 18:37:17 +02001404 if (builtin_sample_mask_id)
1405 active_interface_variables.insert(builtin_sample_mask_id);
Bill Hollingsf591bc02017-06-30 19:10:46 -04001406
Bill Hollings9b4defe2018-06-12 11:41:35 -04001407 // Create structs to hold input, output and uniform variables.
1408 // Do output first to ensure out. is declared at top of entry function.
Bill Hollingse27a5f72017-01-01 14:43:20 -05001409 qual_pos_var_name = "";
Bill Hollingse27a5f72017-01-01 14:43:20 -05001410 stage_out_var_id = add_interface_block(StorageClassOutput);
Chip Daviseb89c3a2019-02-03 23:58:46 -06001411 patch_stage_out_var_id = add_interface_block(StorageClassOutput, true);
Bill Hollings9b4defe2018-06-12 11:41:35 -04001412 stage_in_var_id = add_interface_block(StorageClassInput);
Chip Davise75add42019-02-05 18:13:26 -06001413 if (get_execution_model() == ExecutionModelTessellationEvaluation)
1414 patch_stage_in_var_id = add_interface_block(StorageClassInput, true);
Bill Hollingse27a5f72017-01-01 14:43:20 -05001415
Chip Daviseb89c3a2019-02-03 23:58:46 -06001416 if (get_execution_model() == ExecutionModelTessellationControl)
Chip Daviseb89c3a2019-02-03 23:58:46 -06001417 stage_out_ptr_var_id = add_interface_block_pointer(stage_out_var_id, StorageClassOutput);
Chip Davise75add42019-02-05 18:13:26 -06001418 if (is_tessellation_shader())
Chip Daviseb89c3a2019-02-03 23:58:46 -06001419 stage_in_ptr_var_id = add_interface_block_pointer(stage_in_var_id, StorageClassInput);
Chip Daviseb89c3a2019-02-03 23:58:46 -06001420
Bill Hollingsac238b82018-07-26 00:50:33 -04001421 // Metal vertex functions that define no output must disable rasterization and return void.
Bill Hollings0d6202e2018-07-26 16:40:32 -04001422 if (!stage_out_var_id)
1423 is_rasterization_disabled = true;
Bill Hollingsac238b82018-07-26 00:50:33 -04001424
Bill Hollingse27a5f72017-01-01 14:43:20 -05001425 // Convert the use of global variables to recursively-passed function parameters
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001426 localize_global_variables();
Bill Hollingsac00c602016-10-24 09:24:24 -04001427 extract_global_variables_from_functions();
Bill Hollings8f30f072016-04-07 21:25:51 -04001428
Bill Hollings1c180782017-11-05 21:34:42 -05001429 // Mark any non-stage-in structs to be tightly packed.
1430 mark_packable_structs();
Hans-Kristian Arntzen96492642019-05-23 14:54:04 +02001431 reorder_type_alias();
Bill Hollings1c180782017-11-05 21:34:42 -05001432
Chip Davisf500d2f2019-01-16 17:52:53 -06001433 // Add fixup hooks required by shader inputs and outputs. This needs to happen before
1434 // the loop, so the hooks aren't added multiple times.
1435 fix_up_shader_inputs_outputs();
1436
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +01001437 // If we are using argument buffers, we create argument buffer structures for them here.
1438 // These buffers will be used in the entry point, not the individual resources.
1439 if (msl_options.argument_buffers)
1440 {
1441 if (!msl_options.supports_msl_version(2, 0))
1442 SPIRV_CROSS_THROW("Argument buffers can only be used with MSL 2.0 and up.");
1443 analyze_argument_buffers();
1444 }
1445
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001446 uint32_t pass_count = 0;
1447 do
1448 {
Hans-Kristian Arntzen1d13a3e2022-01-17 14:12:01 +01001449 reset(pass_count);
Bill Hollings8f30f072016-04-07 21:25:51 -04001450
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01001451 // Start bindings at zero.
1452 next_metal_resource_index_buffer = 0;
1453 next_metal_resource_index_texture = 0;
1454 next_metal_resource_index_sampler = 0;
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +02001455 for (auto &id : next_metal_resource_ids)
1456 id = 0;
Hans-Kristian Arntzen6cc96242016-09-17 18:46:10 +02001457
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001458 // Move constructor for this type is broken on GCC 4.9 ...
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001459 buffer.reset();
Bill Hollings8f30f072016-04-07 21:25:51 -04001460
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001461 emit_header();
Lukas Hermanns51be6012019-09-17 15:10:39 -04001462 emit_custom_templates();
Bill Hollingsec054da2021-09-28 19:10:16 -04001463 emit_custom_functions();
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001464 emit_specialization_constants_and_structs();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001465 emit_resources();
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001466 emit_function(get<SPIRFunction>(ir.default_entry_point), Bitset());
Bill Hollings8f30f072016-04-07 21:25:51 -04001467
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001468 pass_count++;
Hans-Kristian Arntzen317144a2019-04-05 12:06:10 +02001469 } while (is_forcing_recompilation());
Bill Hollings8f30f072016-04-07 21:25:51 -04001470
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001471 return buffer.str();
Bill Hollings8f30f072016-04-07 21:25:51 -04001472}
1473
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05001474// Register the need to output any custom functions.
Bill Hollings4c198bb2017-01-20 11:24:44 -05001475void CompilerMSL::preprocess_op_codes()
Bill Hollings103aabf2016-04-06 17:42:27 -04001476{
Bill Hollings2d0d3282017-01-20 11:33:59 -05001477 OpCodePreprocessor preproc(*this);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001478 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), preproc);
Bill Hollings4c198bb2017-01-20 11:24:44 -05001479
Hans-Kristian Arntzen23db7442019-04-09 12:28:46 +02001480 suppress_missing_prototypes = preproc.suppress_missing_prototypes;
Bill Hollings8f6df772017-05-19 18:14:08 -04001481
1482 if (preproc.uses_atomics)
1483 {
1484 add_header_line("#include <metal_atomic>");
1485 add_pragma_line("#pragma clang diagnostic ignored \"-Wunused-variable\"");
1486 }
Bill Hollingsac238b82018-07-26 00:50:33 -04001487
Chip Davis1b6b9702020-10-20 00:54:59 -05001488 // Before MSL 2.1 (2.2 for textures), Metal vertex functions that write to
1489 // resources must disable rasterization and return void.
Bill Hollingsc3d74e12018-07-27 16:53:36 -04001490 if (preproc.uses_resource_write)
Bill Hollings0d6202e2018-07-26 16:40:32 -04001491 is_rasterization_disabled = true;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001492
1493 // Tessellation control shaders are run as compute functions in Metal, and so
1494 // must capture their output to a buffer.
Chip Davis688c5fc2020-02-20 21:38:28 -06001495 if (get_execution_model() == ExecutionModelTessellationControl ||
1496 (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation))
Chip Daviseb89c3a2019-02-03 23:58:46 -06001497 {
1498 is_rasterization_disabled = true;
1499 capture_output_to_buffer = true;
1500 }
Chip Davis9d941572019-05-15 16:03:30 -05001501
1502 if (preproc.needs_subgroup_invocation_id)
1503 needs_subgroup_invocation_id = true;
Chip Davis065b5bd2020-10-20 23:59:30 -05001504 if (preproc.needs_subgroup_size)
1505 needs_subgroup_size = true;
Chip Davisfd738e32020-11-20 15:41:46 -06001506 // build_implicit_builtins() hasn't run yet, and in fact, this needs to execute
1507 // before then so that gl_SampleID will get added; so we also need to check if
1508 // that function would add gl_FragCoord.
1509 if (preproc.needs_sample_id || msl_options.force_sample_rate_shading ||
1510 (is_sample_rate() && (active_input_builtins.get(BuiltInFragCoord) ||
1511 (need_subpass_input && !msl_options.use_framebuffer_fetch_subpasses))))
Chip Davisaca9b682020-11-02 20:56:46 -06001512 needs_sample_id = true;
丛越597f29d2021-10-19 18:45:10 +08001513
丛越d52ec1e2021-10-21 17:46:45 +08001514 if (is_intersection_query())
丛越597f29d2021-10-19 18:45:10 +08001515 {
丛越d52ec1e2021-10-21 17:46:45 +08001516 add_header_line("#if __METAL_VERSION__ >= 230");
1517 add_header_line("#include <metal_raytracing>");
丛越597f29d2021-10-19 18:45:10 +08001518 add_header_line("using namespace metal::raytracing;");
丛越d52ec1e2021-10-21 17:46:45 +08001519 add_header_line("#endif");
丛越597f29d2021-10-19 18:45:10 +08001520 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001521}
1522
Bill Hollings1c180782017-11-05 21:34:42 -05001523// Move the Private and Workgroup global variables to the entry function.
Bill Hollings762947e2016-04-27 19:54:33 +02001524// Non-constant variables cannot have global scope in Metal.
1525void CompilerMSL::localize_global_variables()
1526{
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001527 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001528 auto iter = global_variables.begin();
1529 while (iter != global_variables.end())
1530 {
Bill Hollings1c180782017-11-05 21:34:42 -05001531 uint32_t v_id = *iter;
1532 auto &var = get<SPIRVariable>(v_id);
1533 if (var.storage == StorageClassPrivate || var.storage == StorageClassWorkgroup)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001534 {
Hans-Kristian Arntzen3e584f22019-02-06 10:38:18 +01001535 if (!variable_is_lut(var))
1536 entry_func.add_local_variable(v_id);
Polona Casermanf647e322017-01-16 09:44:40 +01001537 iter = global_variables.erase(iter);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001538 }
1539 else
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001540 iter++;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001541 }
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001542}
1543
1544// For any global variable accessed directly by a function,
1545// extract that variable and add it as an argument to that function.
1546void CompilerMSL::extract_global_variables_from_functions()
1547{
Bill Hollingsac00c602016-10-24 09:24:24 -04001548 // Uniforms
Bill Hollings5ad73f32017-03-19 21:06:21 -04001549 unordered_set<uint32_t> global_var_ids;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001550 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
1551 if (var.storage == StorageClassInput || var.storage == StorageClassOutput ||
1552 var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
1553 var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer)
Bill Hollingsac00c602016-10-24 09:24:24 -04001554 {
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001555 global_var_ids.insert(var.self);
Bill Hollingsac00c602016-10-24 09:24:24 -04001556 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001557 });
Robert Konradbbc1e0c2017-01-26 10:20:42 +01001558
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001559 // Local vars that are declared in the main function and accessed directly by a function
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001560 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Polona Casermana9fb1502017-01-26 20:05:43 +01001561 for (auto &var : entry_func.local_variables)
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001562 if (get<SPIRVariable>(var).storage != StorageClassFunction)
1563 global_var_ids.insert(var);
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001564
Bill Hollingse4f0dde2017-01-31 11:02:44 -05001565 std::set<uint32_t> added_arg_ids;
Bill Hollings5ad73f32017-03-19 21:06:21 -04001566 unordered_set<uint32_t> processed_func_ids;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001567 extract_global_variables_from_function(ir.default_entry_point, added_arg_ids, global_var_ids, processed_func_ids);
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001568}
1569
1570// MSL does not support the use of global variables for shader input content.
1571// For any global variable accessed directly by the specified function, extract that variable,
1572// add it as an argument to that function, and the arg to the added_arg_ids collection.
Bill Hollingse4f0dde2017-01-31 11:02:44 -05001573void CompilerMSL::extract_global_variables_from_function(uint32_t func_id, std::set<uint32_t> &added_arg_ids,
Bill Hollings5ad73f32017-03-19 21:06:21 -04001574 unordered_set<uint32_t> &global_var_ids,
1575 unordered_set<uint32_t> &processed_func_ids)
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001576{
Bill Hollingsac00c602016-10-24 09:24:24 -04001577 // Avoid processing a function more than once
Robert Konrada778c362017-01-15 16:39:03 +01001578 if (processed_func_ids.find(func_id) != processed_func_ids.end())
1579 {
Polona Caserman47808ec2017-01-09 16:23:58 +01001580 // Return function global variables
1581 added_arg_ids = function_global_vars[func_id];
Bill Hollingsac00c602016-10-24 09:24:24 -04001582 return;
Polona Caserman47808ec2017-01-09 16:23:58 +01001583 }
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001584
Bill Hollingsac00c602016-10-24 09:24:24 -04001585 processed_func_ids.insert(func_id);
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001586
Bill Hollingsac00c602016-10-24 09:24:24 -04001587 auto &func = get<SPIRFunction>(func_id);
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001588
Bill Hollingsac00c602016-10-24 09:24:24 -04001589 // Recursively establish global args added to functions on which we depend.
1590 for (auto block : func.blocks)
1591 {
1592 auto &b = get<SPIRBlock>(block);
1593 for (auto &i : b.ops)
1594 {
1595 auto ops = stream(i);
1596 auto op = static_cast<Op>(i.op);
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001597
Bill Hollingsac00c602016-10-24 09:24:24 -04001598 switch (op)
1599 {
1600 case OpLoad:
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01001601 case OpInBoundsAccessChain:
Bill Hollingsac00c602016-10-24 09:24:24 -04001602 case OpAccessChain:
Chip Davis3bfb2f92018-12-03 02:06:33 -06001603 case OpPtrAccessChain:
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02001604 case OpArrayLength:
Bill Hollingsac00c602016-10-24 09:24:24 -04001605 {
1606 uint32_t base_id = ops[2];
1607 if (global_var_ids.find(base_id) != global_var_ids.end())
1608 added_arg_ids.insert(base_id);
Robert Konrada778c362017-01-15 16:39:03 +01001609
Lukas Hermanns50ac6862019-09-18 14:03:54 -04001610 // Use Metal's native frame-buffer fetch API for subpass inputs.
Hans-Kristian Arntzen702e0862018-02-09 12:13:33 +01001611 auto &type = get<SPIRType>(ops[0]);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04001612 if (type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
Chip Davisc20d5942020-10-27 21:42:33 -05001613 (!msl_options.use_framebuffer_fetch_subpasses))
Hans-Kristian Arntzen702e0862018-02-09 12:13:33 +01001614 {
1615 // Implicitly reads gl_FragCoord.
1616 assert(builtin_frag_coord_id != 0);
1617 added_arg_ids.insert(builtin_frag_coord_id);
Chip Davis4cf840e2020-08-27 19:24:20 -05001618 if (msl_options.multiview)
1619 {
1620 // Implicitly reads gl_ViewIndex.
1621 assert(builtin_view_idx_id != 0);
1622 added_arg_ids.insert(builtin_view_idx_id);
1623 }
1624 else if (msl_options.arrayed_subpass_input)
1625 {
1626 // Implicitly reads gl_Layer.
1627 assert(builtin_layer_id != 0);
1628 added_arg_ids.insert(builtin_layer_id);
1629 }
Hans-Kristian Arntzen702e0862018-02-09 12:13:33 +01001630 }
1631
Bill Hollingsac00c602016-10-24 09:24:24 -04001632 break;
1633 }
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001634
Bill Hollingsac00c602016-10-24 09:24:24 -04001635 case OpFunctionCall:
1636 {
Bill Hollingsa68b3272017-12-26 16:32:45 -05001637 // First see if any of the function call args are globals
1638 for (uint32_t arg_idx = 3; arg_idx < i.length; arg_idx++)
1639 {
1640 uint32_t arg_id = ops[arg_idx];
1641 if (global_var_ids.find(arg_id) != global_var_ids.end())
1642 added_arg_ids.insert(arg_id);
1643 }
1644
1645 // Then recurse into the function itself to extract globals used internally in the function
Bill Hollingsac00c602016-10-24 09:24:24 -04001646 uint32_t inner_func_id = ops[2];
Bill Hollingse4f0dde2017-01-31 11:02:44 -05001647 std::set<uint32_t> inner_func_args;
Bill Hollingsac00c602016-10-24 09:24:24 -04001648 extract_global_variables_from_function(inner_func_id, inner_func_args, global_var_ids,
1649 processed_func_ids);
1650 added_arg_ids.insert(inner_func_args.begin(), inner_func_args.end());
1651 break;
1652 }
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001653
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001654 case OpStore:
1655 {
1656 uint32_t base_id = ops[0];
1657 if (global_var_ids.find(base_id) != global_var_ids.end())
1658 added_arg_ids.insert(base_id);
Chip Davis688c5fc2020-02-20 21:38:28 -06001659
1660 uint32_t rvalue_id = ops[1];
1661 if (global_var_ids.find(rvalue_id) != global_var_ids.end())
1662 added_arg_ids.insert(rvalue_id);
1663
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001664 break;
1665 }
1666
Chip Davis3bfb2f92018-12-03 02:06:33 -06001667 case OpSelect:
1668 {
1669 uint32_t base_id = ops[3];
1670 if (global_var_ids.find(base_id) != global_var_ids.end())
1671 added_arg_ids.insert(base_id);
1672 base_id = ops[4];
1673 if (global_var_ids.find(base_id) != global_var_ids.end())
1674 added_arg_ids.insert(base_id);
Chip Davisa046f7a2019-01-08 12:48:40 -06001675 break;
Chip Davis3bfb2f92018-12-03 02:06:33 -06001676 }
1677
Lukas Hermanns50ac6862019-09-18 14:03:54 -04001678 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04001679 case OpImageTexelPointer:
1680 {
1681 // When using the pointer, we need to know which variable it is actually loaded from.
1682 uint32_t base_id = ops[2];
1683 auto *var = maybe_get_backing_variable(base_id);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +02001684 if (var && atomic_image_vars.count(var->self))
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04001685 {
1686 if (global_var_ids.find(base_id) != global_var_ids.end())
1687 added_arg_ids.insert(base_id);
1688 }
1689 break;
1690 }
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04001691
Chip Davisaca9b682020-11-02 20:56:46 -06001692 case OpExtInst:
1693 {
1694 uint32_t extension_set = ops[2];
1695 if (get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
1696 {
1697 auto op_450 = static_cast<GLSLstd450>(ops[3]);
1698 switch (op_450)
1699 {
1700 case GLSLstd450InterpolateAtCentroid:
1701 case GLSLstd450InterpolateAtSample:
1702 case GLSLstd450InterpolateAtOffset:
1703 {
1704 // For these, we really need the stage-in block. It is theoretically possible to pass the
1705 // interpolant object, but a) doing so would require us to create an entirely new variable
1706 // with Interpolant type, and b) if we have a struct or array, handling all the members and
1707 // elements could get unwieldy fast.
1708 added_arg_ids.insert(stage_in_var_id);
1709 break;
1710 }
Hans-Kristian Arntzen4561ecd2021-11-07 11:27:20 +01001711
1712 case GLSLstd450Modf:
1713 case GLSLstd450Frexp:
1714 {
1715 uint32_t base_id = ops[5];
1716 if (global_var_ids.find(base_id) != global_var_ids.end())
1717 added_arg_ids.insert(base_id);
1718 break;
1719 }
1720
Chip Davisaca9b682020-11-02 20:56:46 -06001721 default:
1722 break;
1723 }
1724 }
Hans-Kristian Arntzenef0256c2020-11-11 16:21:18 +01001725 break;
Chip Davisaca9b682020-11-02 20:56:46 -06001726 }
1727
Jan Sikorskif0239bc2020-10-29 10:02:07 +01001728 case OpGroupNonUniformInverseBallot:
1729 {
1730 added_arg_ids.insert(builtin_subgroup_invocation_id_id);
1731 break;
1732 }
1733
1734 case OpGroupNonUniformBallotFindLSB:
1735 case OpGroupNonUniformBallotFindMSB:
1736 {
1737 added_arg_ids.insert(builtin_subgroup_size_id);
1738 break;
1739 }
1740
1741 case OpGroupNonUniformBallotBitCount:
1742 {
1743 auto operation = static_cast<GroupOperation>(ops[3]);
1744 switch (operation)
1745 {
1746 case GroupOperationReduce:
1747 added_arg_ids.insert(builtin_subgroup_size_id);
1748 break;
1749 case GroupOperationInclusiveScan:
1750 case GroupOperationExclusiveScan:
1751 added_arg_ids.insert(builtin_subgroup_invocation_id_id);
1752 break;
1753 default:
1754 break;
1755 }
1756 break;
1757 }
1758
Bill Hollingsac00c602016-10-24 09:24:24 -04001759 default:
1760 break;
1761 }
Hans-Kristian Arntzenbcaae842018-05-16 10:49:30 +02001762
1763 // TODO: Add all other operations which can affect memory.
1764 // We should consider a more unified system here to reduce boiler-plate.
1765 // This kind of analysis is done in several places ...
Bill Hollingsac00c602016-10-24 09:24:24 -04001766 }
1767 }
Robert Konrada778c362017-01-15 16:39:03 +01001768
1769 function_global_vars[func_id] = added_arg_ids;
Bill Hollingsfe8b8602016-07-06 16:55:45 -04001770
Bill Hollingsac00c602016-10-24 09:24:24 -04001771 // Add the global variables as arguments to the function
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001772 if (func_id != ir.default_entry_point)
Bill Hollingsac00c602016-10-24 09:24:24 -04001773 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001774 bool control_point_added_in = false;
1775 bool control_point_added_out = false;
1776 bool patch_added_in = false;
1777 bool patch_added_out = false;
1778
Bill Hollingsac00c602016-10-24 09:24:24 -04001779 for (uint32_t arg_id : added_arg_ids)
1780 {
Bill Hollingse0910312018-06-24 15:06:12 -04001781 auto &var = get<SPIRVariable>(arg_id);
Vadim Shcherbakov6c41f9e2017-12-06 09:51:23 -08001782 uint32_t type_id = var.basetype;
Bill Hollingse0910312018-06-24 15:06:12 -04001783 auto *p_type = &get<SPIRType>(type_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -06001784 BuiltIn bi_type = BuiltIn(get_decoration(arg_id, DecorationBuiltIn));
Bill Hollingsc2e60132016-11-27 15:00:06 -05001785
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001786 bool is_patch = has_decoration(arg_id, DecorationPatch) || is_patch_block(*p_type);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001787 bool is_block = has_decoration(p_type->self, DecorationBlock);
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001788 bool is_control_point_storage =
1789 !is_patch &&
1790 ((is_tessellation_shader() && var.storage == StorageClassInput) ||
1791 (get_execution_model() == ExecutionModelTessellationControl && var.storage == StorageClassOutput));
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001792 bool is_patch_block_storage = is_patch && is_block && var.storage == StorageClassOutput;
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001793 bool is_builtin = is_builtin_variable(var);
1794 bool variable_is_stage_io =
1795 !is_builtin || bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
1796 bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance ||
1797 p_type->basetype == SPIRType::Struct;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001798 bool is_redirected_to_global_stage_io = (is_control_point_storage || is_patch_block_storage) &&
1799 variable_is_stage_io;
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001800
1801 // If output is masked it is not considered part of the global stage IO interface.
1802 if (is_redirected_to_global_stage_io && var.storage == StorageClassOutput)
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02001803 is_redirected_to_global_stage_io = !is_stage_output_variable_masked(var);
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001804
1805 if (is_redirected_to_global_stage_io)
Chip Daviseb89c3a2019-02-03 23:58:46 -06001806 {
1807 // Tessellation control shaders see inputs and per-vertex outputs as arrays.
Chip Davise75add42019-02-05 18:13:26 -06001808 // Similarly, tessellation evaluation shaders see per-vertex inputs as arrays.
Chip Daviseb89c3a2019-02-03 23:58:46 -06001809 // We collected them into a structure; we must pass the array of this
1810 // structure to the function.
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001811 std::string name;
1812 if (is_patch)
1813 name = var.storage == StorageClassInput ? patch_stage_in_var_name : patch_stage_out_var_name;
1814 else
1815 name = var.storage == StorageClassInput ? "gl_in" : "gl_out";
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001816
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +02001817 if (var.storage == StorageClassOutput && has_decoration(p_type->self, DecorationBlock))
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001818 {
1819 // If we're redirecting a block, we might still need to access the original block
1820 // variable if we're masking some members.
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001821 for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(p_type->member_types.size()); mbr_idx++)
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001822 {
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02001823 if (is_stage_output_block_member_masked(var, mbr_idx, true))
Hans-Kristian Arntzendc54f752021-04-09 12:58:21 +02001824 {
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +02001825 func.add_parameter(var.basetype, var.self, true);
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02001826 break;
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001827 }
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001828 }
1829 }
1830
1831 // Tessellation control shaders see inputs and per-vertex outputs as arrays.
1832 // Similarly, tessellation evaluation shaders see per-vertex inputs as arrays.
1833 // We collected them into a structure; we must pass the array of this
1834 // structure to the function.
Chip Daviseb89c3a2019-02-03 23:58:46 -06001835 if (var.storage == StorageClassInput)
1836 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001837 auto &added_in = is_patch ? patch_added_in : control_point_added_in;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001838 if (added_in)
1839 continue;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001840 arg_id = is_patch ? patch_stage_in_var_id : stage_in_ptr_var_id;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001841 added_in = true;
1842 }
1843 else if (var.storage == StorageClassOutput)
1844 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001845 auto &added_out = is_patch ? patch_added_out : control_point_added_out;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001846 if (added_out)
1847 continue;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02001848 arg_id = is_patch ? patch_stage_out_var_id : stage_out_ptr_var_id;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001849 added_out = true;
1850 }
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +02001851
Chip Daviseb89c3a2019-02-03 23:58:46 -06001852 type_id = get<SPIRVariable>(arg_id).basetype;
Chip Daviseb89c3a2019-02-03 23:58:46 -06001853 uint32_t next_id = ir.increase_bound_by(1);
1854 func.add_parameter(type_id, next_id, true);
1855 set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id);
1856
1857 set_name(next_id, name);
1858 }
Hans-Kristian Arntzena59e25d2021-04-07 12:55:26 +02001859 else if (is_builtin && has_decoration(p_type->self, DecorationBlock))
Bill Hollingse0910312018-06-24 15:06:12 -04001860 {
Chip Davisfc02b3d2019-01-08 12:54:40 -06001861 // Get the pointee type
1862 type_id = get_pointee_type_id(type_id);
Bill Hollingse0910312018-06-24 15:06:12 -04001863 p_type = &get<SPIRType>(type_id);
Bill Hollingsc2e60132016-11-27 15:00:06 -05001864
Bill Hollingse0910312018-06-24 15:06:12 -04001865 uint32_t mbr_idx = 0;
1866 for (auto &mbr_type_id : p_type->member_types)
1867 {
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01001868 BuiltIn builtin = BuiltInMax;
Hans-Kristian Arntzene7824c82021-04-06 12:57:00 +02001869 is_builtin = is_member_builtin(*p_type, mbr_idx, &builtin);
Bill Hollings4beefe72018-06-25 11:40:20 -04001870 if (is_builtin && has_active_builtin(builtin, var.storage))
Bill Hollingse0910312018-06-24 15:06:12 -04001871 {
1872 // Add a arg variable with the same type and decorations as the member
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001873 uint32_t next_ids = ir.increase_bound_by(2);
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +02001874 uint32_t ptr_type_id = next_ids + 0;
1875 uint32_t var_id = next_ids + 1;
1876
1877 // Make sure we have an actual pointer type,
1878 // so that we will get the appropriate address space when declaring these builtins.
1879 auto &ptr = set<SPIRType>(ptr_type_id, get<SPIRType>(mbr_type_id));
1880 ptr.self = mbr_type_id;
1881 ptr.storage = var.storage;
1882 ptr.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01001883 ptr.pointer_depth++;
Chip Davis3bfb2f92018-12-03 02:06:33 -06001884 ptr.parent_type = mbr_type_id;
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +02001885
1886 func.add_parameter(mbr_type_id, var_id, true);
1887 set<SPIRVariable>(var_id, ptr_type_id, StorageClassFunction);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001888 ir.meta[var_id].decoration = ir.meta[type_id].members[mbr_idx];
Bill Hollingse0910312018-06-24 15:06:12 -04001889 }
1890 mbr_idx++;
1891 }
1892 }
1893 else
1894 {
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001895 uint32_t next_id = ir.increase_bound_by(1);
Bill Hollingse0910312018-06-24 15:06:12 -04001896 func.add_parameter(type_id, next_id, true);
1897 set<SPIRVariable>(next_id, type_id, StorageClassFunction, 0, arg_id);
1898
1899 // Ensure the existing variable has a valid name and the new variable has all the same meta info
1900 set_name(arg_id, ensure_valid_name(to_name(arg_id), "v"));
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001901 ir.meta[next_id] = ir.meta[arg_id];
Bill Hollingse0910312018-06-24 15:06:12 -04001902 }
Bill Hollingsac00c602016-10-24 09:24:24 -04001903 }
1904 }
Bill Hollings762947e2016-04-27 19:54:33 +02001905}
1906
Bill Hollings1c180782017-11-05 21:34:42 -05001907// For all variables that are some form of non-input-output interface block, mark that all the structs
1908// that are recursively contained within the type referenced by that variable should be packed tightly.
1909void CompilerMSL::mark_packable_structs()
1910{
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001911 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
1912 if (var.storage != StorageClassFunction && !is_hidden_variable(var))
Bill Hollings1c180782017-11-05 21:34:42 -05001913 {
Hans-Kristian Arntzen2fb9aa22019-01-11 09:29:28 +01001914 auto &type = this->get<SPIRType>(var.basetype);
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001915 if (type.pointer &&
1916 (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
1917 type.storage == StorageClassPushConstant || type.storage == StorageClassStorageBuffer) &&
1918 (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock)))
1919 mark_as_packable(type);
Bill Hollings1c180782017-11-05 21:34:42 -05001920 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01001921 });
Bill Hollings1c180782017-11-05 21:34:42 -05001922}
1923
1924// If the specified type is a struct, it and any nested structs
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02001925// are marked as packable with the SPIRVCrossDecorationBufferBlockRepacked decoration,
Bill Hollings1c180782017-11-05 21:34:42 -05001926void CompilerMSL::mark_as_packable(SPIRType &type)
1927{
1928 // If this is not the base type (eg. it's a pointer or array), tunnel down
1929 if (type.parent_type)
1930 {
1931 mark_as_packable(get<SPIRType>(type.parent_type));
1932 return;
1933 }
1934
1935 if (type.basetype == SPIRType::Struct)
1936 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02001937 set_extended_decoration(type.self, SPIRVCrossDecorationBufferBlockRepacked);
Bill Hollings1c180782017-11-05 21:34:42 -05001938
1939 // Recurse
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02001940 uint32_t mbr_cnt = uint32_t(type.member_types.size());
Bill Hollings1c180782017-11-05 21:34:42 -05001941 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
1942 {
1943 uint32_t mbr_type_id = type.member_types[mbr_idx];
1944 auto &mbr_type = get<SPIRType>(mbr_type_id);
1945 mark_as_packable(mbr_type);
Hans-Kristian Arntzen294259e2018-03-05 16:27:04 +01001946 if (mbr_type.type_alias)
1947 {
1948 auto &mbr_type_alias = get<SPIRType>(mbr_type.type_alias);
1949 mark_as_packable(mbr_type_alias);
1950 }
Bill Hollings1c180782017-11-05 21:34:42 -05001951 }
1952 }
1953}
1954
Chip Davis5281d992020-06-13 23:03:30 -05001955// If a shader input exists at the location, it is marked as being used by this shader
Hans-Kristian Arntzenfaf80b02021-04-09 18:55:10 +02001956void CompilerMSL::mark_location_as_used_by_shader(uint32_t location, const SPIRType &type,
1957 StorageClass storage, bool fallback)
Bill Hollings103aabf2016-04-06 17:42:27 -04001958{
Chip Davis688c5fc2020-02-20 21:38:28 -06001959 if (storage != StorageClassInput)
1960 return;
Hans-Kristian Arntzenaa271c12021-02-17 11:29:33 +01001961
1962 uint32_t count = type_to_location_count(type);
1963 for (uint32_t i = 0; i < count; i++)
Hans-Kristian Arntzenfaf80b02021-04-09 18:55:10 +02001964 {
Hans-Kristian Arntzenaa271c12021-02-17 11:29:33 +01001965 location_inputs_in_use.insert(location + i);
Hans-Kristian Arntzenfaf80b02021-04-09 18:55:10 +02001966 if (fallback)
1967 location_inputs_in_use_fallback.insert(location + i);
1968 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001969}
1970
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01001971uint32_t CompilerMSL::get_target_components_for_fragment_location(uint32_t location) const
1972{
1973 auto itr = fragment_output_components.find(location);
1974 if (itr == end(fragment_output_components))
1975 return 4;
1976 else
1977 return itr->second;
1978}
1979
Chip Davis5281d992020-06-13 23:03:30 -05001980uint32_t CompilerMSL::build_extended_vector_type(uint32_t type_id, uint32_t components, SPIRType::BaseType basetype)
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01001981{
1982 uint32_t new_type_id = ir.increase_bound_by(1);
Chip Davis688c5fc2020-02-20 21:38:28 -06001983 auto &old_type = get<SPIRType>(type_id);
1984 auto *type = &set<SPIRType>(new_type_id, old_type);
1985 type->vecsize = components;
Chip Davis5281d992020-06-13 23:03:30 -05001986 if (basetype != SPIRType::Unknown)
Chip Davis688c5fc2020-02-20 21:38:28 -06001987 type->basetype = basetype;
1988 type->self = new_type_id;
1989 type->parent_type = type_id;
1990 type->array.clear();
1991 type->array_size_literal.clear();
1992 type->pointer = false;
1993
1994 if (is_array(old_type))
1995 {
1996 uint32_t array_type_id = ir.increase_bound_by(1);
1997 type = &set<SPIRType>(array_type_id, *type);
1998 type->parent_type = new_type_id;
1999 type->array = old_type.array;
2000 type->array_size_literal = old_type.array_size_literal;
2001 new_type_id = array_type_id;
2002 }
2003
2004 if (old_type.pointer)
2005 {
2006 uint32_t ptr_type_id = ir.increase_bound_by(1);
2007 type = &set<SPIRType>(ptr_type_id, *type);
2008 type->self = new_type_id;
2009 type->parent_type = new_type_id;
2010 type->storage = old_type.storage;
2011 type->pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01002012 type->pointer_depth++;
Chip Davis688c5fc2020-02-20 21:38:28 -06002013 new_type_id = ptr_type_id;
2014 }
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002015
2016 return new_type_id;
2017}
2018
Chip Davisaca9b682020-11-02 20:56:46 -06002019uint32_t CompilerMSL::build_msl_interpolant_type(uint32_t type_id, bool is_noperspective)
2020{
2021 uint32_t new_type_id = ir.increase_bound_by(1);
2022 SPIRType &type = set<SPIRType>(new_type_id, get<SPIRType>(type_id));
2023 type.basetype = SPIRType::Interpolant;
2024 type.parent_type = type_id;
2025 // In Metal, the pull-model interpolant type encodes perspective-vs-no-perspective in the type itself.
2026 // Add this decoration so we know which argument to pass to the template.
2027 if (is_noperspective)
2028 set_decoration(new_type_id, DecorationNoPerspective);
2029 return new_type_id;
2030}
2031
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002032bool CompilerMSL::add_component_variable_to_interface_block(spv::StorageClass storage, const std::string &ib_var_ref,
2033 SPIRVariable &var,
2034 const SPIRType &type,
2035 InterfaceBlockMeta &meta)
2036{
2037 // Deal with Component decorations.
2038 const InterfaceBlockMeta::LocationMeta *location_meta = nullptr;
2039 uint32_t location = ~0u;
2040 if (has_decoration(var.self, DecorationLocation))
2041 {
2042 location = get_decoration(var.self, DecorationLocation);
2043 auto location_meta_itr = meta.location_meta.find(location);
2044 if (location_meta_itr != end(meta.location_meta))
2045 location_meta = &location_meta_itr->second;
2046 }
2047
2048 // Check if we need to pad fragment output to match a certain number of components.
2049 if (location_meta)
2050 {
2051 bool pad_fragment_output = has_decoration(var.self, DecorationLocation) &&
2052 msl_options.pad_fragment_output_components &&
2053 get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput;
2054
2055 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
2056 uint32_t start_component = get_decoration(var.self, DecorationComponent);
2057 uint32_t type_components = type.vecsize;
2058 uint32_t num_components = location_meta->num_components;
2059
2060 if (pad_fragment_output)
2061 {
2062 uint32_t locn = get_decoration(var.self, DecorationLocation);
2063 num_components = std::max(num_components, get_target_components_for_fragment_location(locn));
2064 }
2065
2066 // We have already declared an IO block member as m_location_N.
2067 // Just emit an early-declared variable and fixup as needed.
2068 // Arrays need to be unrolled here since each location might need a different number of components.
2069 entry_func.add_local_variable(var.self);
2070 vars_needing_early_declaration.push_back(var.self);
2071
2072 if (var.storage == StorageClassInput)
2073 {
2074 entry_func.fixup_hooks_in.push_back([=, &type, &var]() {
2075 if (!type.array.empty())
2076 {
2077 uint32_t array_size = to_array_size_literal(type);
2078 for (uint32_t loc_off = 0; loc_off < array_size; loc_off++)
2079 {
2080 statement(to_name(var.self), "[", loc_off, "]", " = ", ib_var_ref,
2081 ".m_location_", location + loc_off,
2082 vector_swizzle(type_components, start_component), ";");
2083 }
2084 }
2085 else
2086 {
2087 statement(to_name(var.self), " = ", ib_var_ref, ".m_location_", location,
2088 vector_swizzle(type_components, start_component), ";");
2089 }
2090 });
2091 }
2092 else
2093 {
2094 entry_func.fixup_hooks_out.push_back([=, &type, &var]() {
2095 if (!type.array.empty())
2096 {
2097 uint32_t array_size = to_array_size_literal(type);
2098 for (uint32_t loc_off = 0; loc_off < array_size; loc_off++)
2099 {
2100 statement(ib_var_ref, ".m_location_", location + loc_off,
2101 vector_swizzle(type_components, start_component), " = ",
2102 to_name(var.self), "[", loc_off, "];");
2103 }
2104 }
2105 else
2106 {
2107 statement(ib_var_ref, ".m_location_", location,
2108 vector_swizzle(type_components, start_component), " = ", to_name(var.self), ";");
2109 }
2110 });
2111 }
2112 return true;
2113 }
2114 else
2115 return false;
2116}
2117
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002118void CompilerMSL::add_plain_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002119 SPIRType &ib_type, SPIRVariable &var, InterfaceBlockMeta &meta)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002120{
2121 bool is_builtin = is_builtin_variable(var);
2122 BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
2123 bool is_flat = has_decoration(var.self, DecorationFlat);
2124 bool is_noperspective = has_decoration(var.self, DecorationNoPerspective);
2125 bool is_centroid = has_decoration(var.self, DecorationCentroid);
2126 bool is_sample = has_decoration(var.self, DecorationSample);
2127
2128 // Add a reference to the variable type to the interface struct.
2129 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
2130 uint32_t type_id = ensure_correct_builtin_type(var.basetype, builtin);
2131 var.basetype = type_id;
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002132
Chip Davis0bb6bbd2019-02-11 17:18:54 -06002133 type_id = get_pointee_type_id(var.basetype);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002134 if (meta.strip_array && is_array(get<SPIRType>(type_id)))
Chip Davis0bb6bbd2019-02-11 17:18:54 -06002135 type_id = get<SPIRType>(type_id).parent_type;
2136 auto &type = get<SPIRType>(type_id);
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002137 uint32_t target_components = 0;
2138 uint32_t type_components = type.vecsize;
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002139
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002140 bool padded_output = false;
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002141 bool padded_input = false;
2142 uint32_t start_component = 0;
2143
2144 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
2145
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002146 if (add_component_variable_to_interface_block(storage, ib_var_ref, var, type, meta))
2147 return;
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002148
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01002149 bool pad_fragment_output = has_decoration(var.self, DecorationLocation) &&
2150 msl_options.pad_fragment_output_components &&
Hans-Kristian Arntzenc024e242020-01-07 17:02:12 +01002151 get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput;
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002152
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002153 if (pad_fragment_output)
Hans-Kristian Arntzenc024e242020-01-07 17:02:12 +01002154 {
2155 uint32_t locn = get_decoration(var.self, DecorationLocation);
2156 target_components = get_target_components_for_fragment_location(locn);
2157 if (type_components < target_components)
2158 {
2159 // Make a new type here.
2160 type_id = build_extended_vector_type(type_id, target_components);
2161 padded_output = true;
2162 }
2163 }
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002164
Chip Davisaca9b682020-11-02 20:56:46 -06002165 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2166 ib_type.member_types.push_back(build_msl_interpolant_type(type_id, is_noperspective));
2167 else
2168 ib_type.member_types.push_back(type_id);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002169
2170 // Give the member a name
2171 string mbr_name = ensure_valid_name(to_expression(var.self), "m");
2172 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2173
2174 // Update the original variable reference to include the structure reference
2175 string qual_var_name = ib_var_ref + "." + mbr_name;
Chip Davisaca9b682020-11-02 20:56:46 -06002176 // If using pull-model interpolation, need to add a call to the correct interpolation method.
2177 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2178 {
2179 if (is_centroid)
2180 qual_var_name += ".interpolate_at_centroid()";
2181 else if (is_sample)
2182 qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
2183 else
2184 qual_var_name += ".interpolate_at_center()";
2185 }
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002186
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002187 if (padded_output || padded_input)
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002188 {
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002189 entry_func.add_local_variable(var.self);
2190 vars_needing_early_declaration.push_back(var.self);
2191
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002192 if (padded_output)
2193 {
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01002194 entry_func.fixup_hooks_out.push_back([=, &var]() {
2195 statement(qual_var_name, vector_swizzle(type_components, start_component), " = ", to_name(var.self),
2196 ";");
2197 });
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002198 }
2199 else
2200 {
2201 entry_func.fixup_hooks_in.push_back([=, &var]() {
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01002202 statement(to_name(var.self), " = ", qual_var_name, vector_swizzle(type_components, start_component),
2203 ";");
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002204 });
2205 }
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002206 }
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002207 else if (!meta.strip_array)
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002208 ir.meta[var.self].decoration.qualified_alias = qual_var_name;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002209
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02002210 if (var.storage == StorageClassOutput && var.initializer != ID(0))
Hans-Kristian Arntzen3e098792019-01-30 10:29:08 +01002211 {
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002212 if (padded_output || padded_input)
2213 {
2214 entry_func.fixup_hooks_in.push_back(
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01002215 [=, &var]() { statement(to_name(var.self), " = ", to_expression(var.initializer), ";"); });
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002216 }
2217 else
2218 {
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002219 if (meta.strip_array)
2220 {
2221 entry_func.fixup_hooks_in.push_back([=, &var]() {
2222 uint32_t index = get_extended_decoration(var.self, SPIRVCrossDecorationInterfaceMemberIndex);
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02002223 auto invocation = to_tesc_invocation_id();
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002224 statement(to_expression(stage_out_ptr_var_id), "[",
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02002225 invocation, "].",
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002226 to_member_name(ib_type, index), " = ", to_expression(var.initializer), "[",
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02002227 invocation, "];");
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002228 });
2229 }
2230 else
2231 {
2232 entry_func.fixup_hooks_in.push_back([=, &var]() {
2233 statement(qual_var_name, " = ", to_expression(var.initializer), ";");
2234 });
2235 }
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002236 }
Hans-Kristian Arntzen3e098792019-01-30 10:29:08 +01002237 }
2238
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002239 // Copy the variable location from the original variable to the member
2240 if (get_decoration_bitset(var.self).get(DecorationLocation))
2241 {
2242 uint32_t locn = get_decoration(var.self, DecorationLocation);
Bill Hollings548a23d2021-09-20 17:57:11 -04002243 uint32_t comp = get_decoration(var.self, DecorationComponent);
Chip Davis5281d992020-06-13 23:03:30 -05002244 if (storage == StorageClassInput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002245 {
Bill Hollings548a23d2021-09-20 17:57:11 -04002246 type_id = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array);
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002247 var.basetype = type_id;
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002248
Chip Davis1919eb12019-02-11 16:07:43 -06002249 type_id = get_pointee_type_id(type_id);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002250 if (meta.strip_array && is_array(get<SPIRType>(type_id)))
Chip Davis1919eb12019-02-11 16:07:43 -06002251 type_id = get<SPIRType>(type_id).parent_type;
Chip Davisaca9b682020-11-02 20:56:46 -06002252 if (pull_model_inputs.count(var.self))
2253 ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(type_id, is_noperspective);
2254 else
2255 ib_type.member_types[ib_mbr_idx] = type_id;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002256 }
2257 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Bill Hollings548a23d2021-09-20 17:57:11 -04002258 if (comp)
2259 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
Chip Davis688c5fc2020-02-20 21:38:28 -06002260 mark_location_as_used_by_shader(locn, get<SPIRType>(type_id), storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002261 }
Bill Hollings4ebd56b2021-11-03 00:03:26 -04002262 else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
Chip Davis5069ec72019-02-20 22:10:59 -06002263 {
Chip Davis5281d992020-06-13 23:03:30 -05002264 uint32_t locn = inputs_by_builtin[builtin].location;
Chip Davis5069ec72019-02-20 22:10:59 -06002265 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002266 mark_location_as_used_by_shader(locn, type, storage);
Chip Davis5069ec72019-02-20 22:10:59 -06002267 }
2268
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002269 if (get_decoration_bitset(var.self).get(DecorationComponent))
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002270 {
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002271 uint32_t component = get_decoration(var.self, DecorationComponent);
2272 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, component);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002273 }
2274
2275 if (get_decoration_bitset(var.self).get(DecorationIndex))
2276 {
2277 uint32_t index = get_decoration(var.self, DecorationIndex);
2278 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index);
2279 }
2280
2281 // Mark the member as builtin if needed
2282 if (is_builtin)
2283 {
2284 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
Chip Davisf3267db2019-02-22 15:26:00 -06002285 if (builtin == BuiltInPosition && storage == StorageClassOutput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002286 qual_pos_var_name = qual_var_name;
2287 }
2288
2289 // Copy interpolation decorations if needed
Chip Davisaca9b682020-11-02 20:56:46 -06002290 if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
2291 {
2292 if (is_flat)
2293 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
2294 if (is_noperspective)
2295 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
2296 if (is_centroid)
2297 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
2298 if (is_sample)
2299 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
2300 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06002301
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002302 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002303}
2304
2305void CompilerMSL::add_composite_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01002306 SPIRType &ib_type, SPIRVariable &var,
2307 InterfaceBlockMeta &meta)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002308{
2309 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002310 auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002311 uint32_t elem_cnt = 0;
2312
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02002313 if (add_component_variable_to_interface_block(storage, ib_var_ref, var, var_type, meta))
2314 return;
2315
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002316 if (is_matrix(var_type))
2317 {
2318 if (is_array(var_type))
2319 SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables.");
2320
2321 elem_cnt = var_type.columns;
2322 }
2323 else if (is_array(var_type))
2324 {
2325 if (var_type.array.size() != 1)
2326 SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables.");
2327
2328 elem_cnt = to_array_size_literal(var_type);
2329 }
2330
Chip Davis5069ec72019-02-20 22:10:59 -06002331 bool is_builtin = is_builtin_variable(var);
2332 BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002333 bool is_flat = has_decoration(var.self, DecorationFlat);
2334 bool is_noperspective = has_decoration(var.self, DecorationNoPerspective);
2335 bool is_centroid = has_decoration(var.self, DecorationCentroid);
2336 bool is_sample = has_decoration(var.self, DecorationSample);
2337
2338 auto *usable_type = &var_type;
2339 if (usable_type->pointer)
2340 usable_type = &get<SPIRType>(usable_type->parent_type);
2341 while (is_array(*usable_type) || is_matrix(*usable_type))
2342 usable_type = &get<SPIRType>(usable_type->parent_type);
2343
Chip Davis7a7e2102019-02-20 20:23:02 -06002344 // If a builtin, force it to have the proper name.
Chip Davis5069ec72019-02-20 22:10:59 -06002345 if (is_builtin)
Chip Davis7a7e2102019-02-20 20:23:02 -06002346 set_name(var.self, builtin_to_glsl(builtin, StorageClassFunction));
Chip Davis7a7e2102019-02-20 20:23:02 -06002347
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002348 bool flatten_from_ib_var = false;
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +01002349 string flatten_from_ib_mbr_name;
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002350
Hans-Kristian Arntzen99084dc2019-12-02 15:52:00 +01002351 if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance)
Hans-Kristian Arntzend0953f62019-10-25 13:54:38 +02002352 {
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002353 // Also declare [[clip_distance]] attribute here.
2354 uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size());
2355 ib_type.member_types.push_back(get_variable_data_type_id(var));
2356 set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance);
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +01002357
2358 flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput);
2359 set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002360
2361 // When we flatten, we flatten directly from the "out" struct,
2362 // not from a function variable.
2363 flatten_from_ib_var = true;
Hans-Kristian Arntzenebf46362020-04-20 09:48:20 +02002364
2365 if (!msl_options.enable_clip_distance_user_varying)
2366 return;
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002367 }
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002368 else if (!meta.strip_array)
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002369 {
2370 // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped.
Hans-Kristian Arntzend0953f62019-10-25 13:54:38 +02002371 entry_func.add_local_variable(var.self);
2372 // We need to declare the variable early and at entry-point scope.
2373 vars_needing_early_declaration.push_back(var.self);
2374 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002375
2376 for (uint32_t i = 0; i < elem_cnt; i++)
2377 {
2378 // Add a reference to the variable type to the interface struct.
2379 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002380
2381 uint32_t target_components = 0;
2382 bool padded_output = false;
2383 uint32_t type_id = usable_type->self;
2384
2385 // Check if we need to pad fragment output to match a certain number of components.
2386 if (get_decoration_bitset(var.self).get(DecorationLocation) && msl_options.pad_fragment_output_components &&
2387 get_entry_point().model == ExecutionModelFragment && storage == StorageClassOutput)
2388 {
2389 uint32_t locn = get_decoration(var.self, DecorationLocation) + i;
2390 target_components = get_target_components_for_fragment_location(locn);
2391 if (usable_type->vecsize < target_components)
2392 {
2393 // Make a new type here.
2394 type_id = build_extended_vector_type(usable_type->self, target_components);
2395 padded_output = true;
2396 }
2397 }
2398
Chip Davisaca9b682020-11-02 20:56:46 -06002399 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2400 ib_type.member_types.push_back(build_msl_interpolant_type(get_pointee_type_id(type_id), is_noperspective));
2401 else
2402 ib_type.member_types.push_back(get_pointee_type_id(type_id));
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002403
2404 // Give the member a name
2405 string mbr_name = ensure_valid_name(join(to_expression(var.self), "_", i), "m");
2406 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2407
2408 // There is no qualified alias since we need to flatten the internal array on return.
2409 if (get_decoration_bitset(var.self).get(DecorationLocation))
2410 {
2411 uint32_t locn = get_decoration(var.self, DecorationLocation) + i;
Hans-Kristian Arntzena64ddcd2021-05-21 12:31:33 +02002412 uint32_t comp = get_decoration(var.self, DecorationComponent);
Chip Davis5281d992020-06-13 23:03:30 -05002413 if (storage == StorageClassInput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002414 {
Bill Hollings548a23d2021-09-20 17:57:11 -04002415 var.basetype = ensure_correct_input_type(var.basetype, locn, comp, 0, meta.strip_array);
2416 uint32_t mbr_type_id = ensure_correct_input_type(usable_type->self, locn, comp, 0, meta.strip_array);
Chip Davisaca9b682020-11-02 20:56:46 -06002417 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2418 ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
2419 else
2420 ib_type.member_types[ib_mbr_idx] = mbr_type_id;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002421 }
2422 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Hans-Kristian Arntzena64ddcd2021-05-21 12:31:33 +02002423 if (comp)
2424 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
Chip Davis688c5fc2020-02-20 21:38:28 -06002425 mark_location_as_used_by_shader(locn, *usable_type, storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002426 }
Bill Hollings4ebd56b2021-11-03 00:03:26 -04002427 else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
Chip Davis5069ec72019-02-20 22:10:59 -06002428 {
Chip Davis5281d992020-06-13 23:03:30 -05002429 uint32_t locn = inputs_by_builtin[builtin].location + i;
Chip Davis5069ec72019-02-20 22:10:59 -06002430 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002431 mark_location_as_used_by_shader(locn, *usable_type, storage);
Chip Davis5069ec72019-02-20 22:10:59 -06002432 }
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02002433 else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance))
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002434 {
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02002435 // Declare the Clip/CullDistance as [[user(clip/cullN)]].
2436 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
2437 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002438 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002439
2440 if (get_decoration_bitset(var.self).get(DecorationIndex))
2441 {
2442 uint32_t index = get_decoration(var.self, DecorationIndex);
2443 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, index);
2444 }
2445
Chip Davisaca9b682020-11-02 20:56:46 -06002446 if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
2447 {
2448 // Copy interpolation decorations if needed
2449 if (is_flat)
2450 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
2451 if (is_noperspective)
2452 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
2453 if (is_centroid)
2454 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
2455 if (is_sample)
2456 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
2457 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002458
Chip Daviseb89c3a2019-02-03 23:58:46 -06002459 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
2460
Hans-Kristian Arntzend0953f62019-10-25 13:54:38 +02002461 // Only flatten/unflatten IO composites for non-tessellation cases where arrays are not stripped.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002462 if (!meta.strip_array)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002463 {
Chip Davis08863c12019-02-15 17:22:37 -06002464 switch (storage)
2465 {
2466 case StorageClassInput:
Chip Davisaca9b682020-11-02 20:56:46 -06002467 entry_func.fixup_hooks_in.push_back([=, &var]() {
2468 if (pull_model_inputs.count(var.self))
2469 {
2470 string lerp_call;
2471 if (is_centroid)
2472 lerp_call = ".interpolate_at_centroid()";
2473 else if (is_sample)
2474 lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
2475 else
2476 lerp_call = ".interpolate_at_center()";
2477 statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, lerp_call, ";");
2478 }
2479 else
2480 {
2481 statement(to_name(var.self), "[", i, "] = ", ib_var_ref, ".", mbr_name, ";");
2482 }
2483 });
Chip Davis08863c12019-02-15 17:22:37 -06002484 break;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002485
Chip Davis08863c12019-02-15 17:22:37 -06002486 case StorageClassOutput:
2487 entry_func.fixup_hooks_out.push_back([=, &var]() {
2488 if (padded_output)
2489 {
2490 auto &padded_type = this->get<SPIRType>(type_id);
2491 statement(
2492 ib_var_ref, ".", mbr_name, " = ",
2493 remap_swizzle(padded_type, usable_type->vecsize, join(to_name(var.self), "[", i, "]")),
2494 ";");
2495 }
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002496 else if (flatten_from_ib_var)
Hans-Kristian Arntzen7a411252020-01-16 15:20:59 +01002497 statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i,
2498 "];");
Chip Davis08863c12019-02-15 17:22:37 -06002499 else
2500 statement(ib_var_ref, ".", mbr_name, " = ", to_name(var.self), "[", i, "];");
2501 });
2502 break;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002503
Chip Davis08863c12019-02-15 17:22:37 -06002504 default:
2505 break;
2506 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002507 }
2508 }
2509}
2510
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002511void CompilerMSL::add_composite_member_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
2512 SPIRType &ib_type, SPIRVariable &var,
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002513 uint32_t mbr_idx, InterfaceBlockMeta &meta)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002514{
2515 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002516 auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002517
Hans-Kristian Arntzen99084dc2019-12-02 15:52:00 +01002518 BuiltIn builtin = BuiltInMax;
Chip Davis5069ec72019-02-20 22:10:59 -06002519 bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002520 bool is_flat =
2521 has_member_decoration(var_type.self, mbr_idx, DecorationFlat) || has_decoration(var.self, DecorationFlat);
2522 bool is_noperspective = has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) ||
2523 has_decoration(var.self, DecorationNoPerspective);
2524 bool is_centroid = has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) ||
2525 has_decoration(var.self, DecorationCentroid);
2526 bool is_sample =
2527 has_member_decoration(var_type.self, mbr_idx, DecorationSample) || has_decoration(var.self, DecorationSample);
2528
2529 uint32_t mbr_type_id = var_type.member_types[mbr_idx];
2530 auto &mbr_type = get<SPIRType>(mbr_type_id);
2531 uint32_t elem_cnt = 0;
2532
2533 if (is_matrix(mbr_type))
2534 {
2535 if (is_array(mbr_type))
2536 SPIRV_CROSS_THROW("MSL cannot emit arrays-of-matrices in input and output variables.");
2537
2538 elem_cnt = mbr_type.columns;
2539 }
2540 else if (is_array(mbr_type))
2541 {
2542 if (mbr_type.array.size() != 1)
2543 SPIRV_CROSS_THROW("MSL cannot emit arrays-of-arrays in input and output variables.");
2544
2545 elem_cnt = to_array_size_literal(mbr_type);
2546 }
2547
2548 auto *usable_type = &mbr_type;
2549 if (usable_type->pointer)
2550 usable_type = &get<SPIRType>(usable_type->parent_type);
2551 while (is_array(*usable_type) || is_matrix(*usable_type))
2552 usable_type = &get<SPIRType>(usable_type->parent_type);
2553
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002554 bool flatten_from_ib_var = false;
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +01002555 string flatten_from_ib_mbr_name;
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002556
Hans-Kristian Arntzen99084dc2019-12-02 15:52:00 +01002557 if (storage == StorageClassOutput && is_builtin && builtin == BuiltInClipDistance)
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002558 {
2559 // Also declare [[clip_distance]] attribute here.
2560 uint32_t clip_array_mbr_idx = uint32_t(ib_type.member_types.size());
2561 ib_type.member_types.push_back(mbr_type_id);
2562 set_member_decoration(ib_type.self, clip_array_mbr_idx, DecorationBuiltIn, BuiltInClipDistance);
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +01002563
2564 flatten_from_ib_mbr_name = builtin_to_glsl(BuiltInClipDistance, StorageClassOutput);
2565 set_member_name(ib_type.self, clip_array_mbr_idx, flatten_from_ib_mbr_name);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002566
2567 // When we flatten, we flatten directly from the "out" struct,
2568 // not from a function variable.
2569 flatten_from_ib_var = true;
Hans-Kristian Arntzenebf46362020-04-20 09:48:20 +02002570
2571 if (!msl_options.enable_clip_distance_user_varying)
2572 return;
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002573 }
2574
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002575 for (uint32_t i = 0; i < elem_cnt; i++)
2576 {
2577 // Add a reference to the variable type to the interface struct.
2578 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
Chip Davisaca9b682020-11-02 20:56:46 -06002579 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2580 ib_type.member_types.push_back(build_msl_interpolant_type(usable_type->self, is_noperspective));
2581 else
2582 ib_type.member_types.push_back(usable_type->self);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002583
2584 // Give the member a name
2585 string mbr_name = ensure_valid_name(join(to_qualified_member_name(var_type, mbr_idx), "_", i), "m");
2586 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2587
2588 if (has_member_decoration(var_type.self, mbr_idx, DecorationLocation))
2589 {
2590 uint32_t locn = get_member_decoration(var_type.self, mbr_idx, DecorationLocation) + i;
2591 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002592 mark_location_as_used_by_shader(locn, *usable_type, storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002593 }
2594 else if (has_decoration(var.self, DecorationLocation))
2595 {
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002596 uint32_t locn = get_accumulated_member_location(var, mbr_idx, meta.strip_array) + i;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002597 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002598 mark_location_as_used_by_shader(locn, *usable_type, storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002599 }
Bill Hollings4ebd56b2021-11-03 00:03:26 -04002600 else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
Chip Davis5069ec72019-02-20 22:10:59 -06002601 {
Chip Davis5281d992020-06-13 23:03:30 -05002602 uint32_t locn = inputs_by_builtin[builtin].location + i;
Chip Davis5069ec72019-02-20 22:10:59 -06002603 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002604 mark_location_as_used_by_shader(locn, *usable_type, storage);
Chip Davis5069ec72019-02-20 22:10:59 -06002605 }
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02002606 else if (is_builtin && (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance))
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002607 {
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02002608 // Declare the Clip/CullDistance as [[user(clip/cullN)]].
2609 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
2610 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationIndex, i);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002611 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002612
2613 if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent))
2614 SPIRV_CROSS_THROW("DecorationComponent on matrices and arrays make little sense.");
2615
Chip Davisaca9b682020-11-02 20:56:46 -06002616 if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
2617 {
2618 // Copy interpolation decorations if needed
2619 if (is_flat)
2620 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
2621 if (is_noperspective)
2622 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
2623 if (is_centroid)
2624 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
2625 if (is_sample)
2626 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
2627 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002628
Chip Daviseb89c3a2019-02-03 23:58:46 -06002629 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
2630 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, mbr_idx);
2631
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002632 // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02002633 if (!meta.strip_array && meta.allow_local_declaration)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002634 {
Chip Davis08863c12019-02-15 17:22:37 -06002635 switch (storage)
2636 {
2637 case StorageClassInput:
2638 entry_func.fixup_hooks_in.push_back([=, &var, &var_type]() {
Chip Davisaca9b682020-11-02 20:56:46 -06002639 if (pull_model_inputs.count(var.self))
2640 {
2641 string lerp_call;
2642 if (is_centroid)
2643 lerp_call = ".interpolate_at_centroid()";
2644 else if (is_sample)
2645 lerp_call = join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
2646 else
2647 lerp_call = ".interpolate_at_center()";
2648 statement(to_name(var.self), ".", to_member_name(var_type, mbr_idx), "[", i, "] = ", ib_var_ref,
2649 ".", mbr_name, lerp_call, ";");
2650 }
2651 else
2652 {
2653 statement(to_name(var.self), ".", to_member_name(var_type, mbr_idx), "[", i, "] = ", ib_var_ref,
2654 ".", mbr_name, ";");
2655 }
Chip Davis08863c12019-02-15 17:22:37 -06002656 });
2657 break;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002658
Chip Davis08863c12019-02-15 17:22:37 -06002659 case StorageClassOutput:
2660 entry_func.fixup_hooks_out.push_back([=, &var, &var_type]() {
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002661 if (flatten_from_ib_var)
2662 {
Hans-Kristian Arntzen7a411252020-01-16 15:20:59 +01002663 statement(ib_var_ref, ".", mbr_name, " = ", ib_var_ref, ".", flatten_from_ib_mbr_name, "[", i,
2664 "];");
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01002665 }
2666 else
2667 {
2668 statement(ib_var_ref, ".", mbr_name, " = ", to_name(var.self), ".",
2669 to_member_name(var_type, mbr_idx), "[", i, "];");
2670 }
Chip Davis08863c12019-02-15 17:22:37 -06002671 });
2672 break;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002673
Chip Davis08863c12019-02-15 17:22:37 -06002674 default:
2675 break;
2676 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002677 }
2678 }
2679}
2680
2681void CompilerMSL::add_plain_member_variable_to_interface_block(StorageClass storage, const string &ib_var_ref,
Chip Daviseb89c3a2019-02-03 23:58:46 -06002682 SPIRType &ib_type, SPIRVariable &var, uint32_t mbr_idx,
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002683 InterfaceBlockMeta &meta)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002684{
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002685 auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002686 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
2687
2688 BuiltIn builtin = BuiltInMax;
2689 bool is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
2690 bool is_flat =
2691 has_member_decoration(var_type.self, mbr_idx, DecorationFlat) || has_decoration(var.self, DecorationFlat);
2692 bool is_noperspective = has_member_decoration(var_type.self, mbr_idx, DecorationNoPerspective) ||
2693 has_decoration(var.self, DecorationNoPerspective);
2694 bool is_centroid = has_member_decoration(var_type.self, mbr_idx, DecorationCentroid) ||
2695 has_decoration(var.self, DecorationCentroid);
2696 bool is_sample =
2697 has_member_decoration(var_type.self, mbr_idx, DecorationSample) || has_decoration(var.self, DecorationSample);
2698
2699 // Add a reference to the member to the interface struct.
2700 uint32_t mbr_type_id = var_type.member_types[mbr_idx];
2701 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
2702 mbr_type_id = ensure_correct_builtin_type(mbr_type_id, builtin);
2703 var_type.member_types[mbr_idx] = mbr_type_id;
Chip Davisaca9b682020-11-02 20:56:46 -06002704 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2705 ib_type.member_types.push_back(build_msl_interpolant_type(mbr_type_id, is_noperspective));
2706 else
2707 ib_type.member_types.push_back(mbr_type_id);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002708
2709 // Give the member a name
2710 string mbr_name = ensure_valid_name(to_qualified_member_name(var_type, mbr_idx), "m");
2711 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2712
2713 // Update the original variable reference to include the structure reference
2714 string qual_var_name = ib_var_ref + "." + mbr_name;
Chip Davisaca9b682020-11-02 20:56:46 -06002715 // If using pull-model interpolation, need to add a call to the correct interpolation method.
2716 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2717 {
2718 if (is_centroid)
2719 qual_var_name += ".interpolate_at_centroid()";
2720 else if (is_sample)
2721 qual_var_name += join(".interpolate_at_sample(", to_expression(builtin_sample_id_id), ")");
2722 else
2723 qual_var_name += ".interpolate_at_center()";
2724 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002725
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002726 bool flatten_stage_out = false;
2727
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002728 if (is_builtin && !meta.strip_array)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002729 {
2730 // For the builtin gl_PerVertex, we cannot treat it as a block anyways,
2731 // so redirect to qualified name.
2732 set_member_qualified_name(var_type.self, mbr_idx, qual_var_name);
2733 }
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02002734 else if (!meta.strip_array && meta.allow_local_declaration)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002735 {
2736 // Unflatten or flatten from [[stage_in]] or [[stage_out]] as appropriate.
2737 switch (storage)
2738 {
2739 case StorageClassInput:
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002740 entry_func.fixup_hooks_in.push_back([=, &var, &var_type]() {
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002741 statement(to_name(var.self), ".", to_member_name(var_type, mbr_idx), " = ", qual_var_name, ";");
2742 });
2743 break;
2744
2745 case StorageClassOutput:
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002746 flatten_stage_out = true;
Hans-Kristian Arntzenb8033d72019-01-14 14:53:47 +01002747 entry_func.fixup_hooks_out.push_back([=, &var, &var_type]() {
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002748 statement(qual_var_name, " = ", to_name(var.self), ".", to_member_name(var_type, mbr_idx), ";");
2749 });
2750 break;
2751
2752 default:
2753 break;
2754 }
2755 }
2756
2757 // Copy the variable location from the original variable to the member
2758 if (has_member_decoration(var_type.self, mbr_idx, DecorationLocation))
2759 {
2760 uint32_t locn = get_member_decoration(var_type.self, mbr_idx, DecorationLocation);
Bill Hollings548a23d2021-09-20 17:57:11 -04002761 uint32_t comp = get_member_decoration(var_type.self, mbr_idx, DecorationComponent);
Chip Davis5281d992020-06-13 23:03:30 -05002762 if (storage == StorageClassInput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002763 {
Bill Hollings548a23d2021-09-20 17:57:11 -04002764 mbr_type_id = ensure_correct_input_type(mbr_type_id, locn, comp, 0, meta.strip_array);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002765 var_type.member_types[mbr_idx] = mbr_type_id;
Chip Davisaca9b682020-11-02 20:56:46 -06002766 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2767 ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
2768 else
2769 ib_type.member_types[ib_mbr_idx] = mbr_type_id;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002770 }
2771 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002772 mark_location_as_used_by_shader(locn, get<SPIRType>(mbr_type_id), storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002773 }
2774 else if (has_decoration(var.self, DecorationLocation))
2775 {
2776 // The block itself might have a location and in this case, all members of the block
2777 // receive incrementing locations.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01002778 uint32_t locn = get_accumulated_member_location(var, mbr_idx, meta.strip_array);
Chip Davis5281d992020-06-13 23:03:30 -05002779 if (storage == StorageClassInput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002780 {
Bill Hollings548a23d2021-09-20 17:57:11 -04002781 mbr_type_id = ensure_correct_input_type(mbr_type_id, locn, 0, 0, meta.strip_array);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002782 var_type.member_types[mbr_idx] = mbr_type_id;
Chip Davisaca9b682020-11-02 20:56:46 -06002783 if (storage == StorageClassInput && pull_model_inputs.count(var.self))
2784 ib_type.member_types[ib_mbr_idx] = build_msl_interpolant_type(mbr_type_id, is_noperspective);
2785 else
2786 ib_type.member_types[ib_mbr_idx] = mbr_type_id;
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002787 }
2788 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002789 mark_location_as_used_by_shader(locn, get<SPIRType>(mbr_type_id), storage);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002790 }
Bill Hollings4ebd56b2021-11-03 00:03:26 -04002791 else if (is_builtin && is_tessellation_shader() && storage == StorageClassInput && inputs_by_builtin.count(builtin))
Chip Davis5069ec72019-02-20 22:10:59 -06002792 {
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01002793 uint32_t locn = 0;
Chip Davis5281d992020-06-13 23:03:30 -05002794 auto builtin_itr = inputs_by_builtin.find(builtin);
2795 if (builtin_itr != end(inputs_by_builtin))
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01002796 locn = builtin_itr->second.location;
Chip Davis5069ec72019-02-20 22:10:59 -06002797 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002798 mark_location_as_used_by_shader(locn, get<SPIRType>(mbr_type_id), storage);
Chip Davis5069ec72019-02-20 22:10:59 -06002799 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002800
2801 // Copy the component location, if present.
2802 if (has_member_decoration(var_type.self, mbr_idx, DecorationComponent))
2803 {
2804 uint32_t comp = get_member_decoration(var_type.self, mbr_idx, DecorationComponent);
2805 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationComponent, comp);
2806 }
2807
2808 // Mark the member as builtin if needed
2809 if (is_builtin)
2810 {
2811 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
Chip Davisf3267db2019-02-22 15:26:00 -06002812 if (builtin == BuiltInPosition && storage == StorageClassOutput)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002813 qual_pos_var_name = qual_var_name;
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002814 }
Hans-Kristian Arntzena1c784f2021-01-04 11:58:50 +01002815
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002816 const SPIRConstant *c = nullptr;
2817 if (!flatten_stage_out && var.storage == StorageClassOutput &&
2818 var.initializer != ID(0) && (c = maybe_get<SPIRConstant>(var.initializer)))
2819 {
2820 if (meta.strip_array)
Hans-Kristian Arntzena1c784f2021-01-04 11:58:50 +01002821 {
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002822 entry_func.fixup_hooks_in.push_back([=, &var]() {
2823 auto &type = this->get<SPIRType>(var.basetype);
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02002824 uint32_t index = get_extended_member_decoration(var.self, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex);
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002825
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02002826 auto invocation = to_tesc_invocation_id();
2827 auto constant_chain = join(to_expression(var.initializer), "[", invocation, "]");
Hans-Kristian Arntzenc1edd352021-04-16 11:45:50 +02002828 statement(to_expression(stage_out_ptr_var_id), "[",
2829 invocation, "].",
2830 to_member_name(ib_type, index), " = ",
2831 constant_chain, ".", to_member_name(type, mbr_idx), ";");
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01002832 });
2833 }
2834 else
2835 {
2836 entry_func.fixup_hooks_in.push_back([=]() {
2837 statement(qual_var_name, " = ", constant_expression(
2838 this->get<SPIRConstant>(c->subconstants[mbr_idx])), ";");
2839 });
Hans-Kristian Arntzena1c784f2021-01-04 11:58:50 +01002840 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002841 }
2842
Chip Davisaca9b682020-11-02 20:56:46 -06002843 if (storage != StorageClassInput || !pull_model_inputs.count(var.self))
2844 {
2845 // Copy interpolation decorations if needed
2846 if (is_flat)
2847 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
2848 if (is_noperspective)
2849 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
2850 if (is_centroid)
2851 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
2852 if (is_sample)
2853 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
2854 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06002855
2856 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceOrigID, var.self);
2857 set_extended_member_decoration(ib_type.self, ib_mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, mbr_idx);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01002858}
2859
Chip Davisf3c09422019-02-22 12:11:17 -06002860// In Metal, the tessellation levels are stored as tightly packed half-precision floating point values.
2861// But, stage-in attribute offsets and strides must be multiples of four, so we can't pass the levels
2862// individually. Therefore, we must pass them as vectors. Triangles get a single float4, with the outer
2863// levels in 'xyz' and the inner level in 'w'. Quads get a float4 containing the outer levels and a
2864// float2 containing the inner levels.
2865void CompilerMSL::add_tess_level_input_to_interface_block(const std::string &ib_var_ref, SPIRType &ib_type,
2866 SPIRVariable &var)
2867{
2868 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
2869 auto &var_type = get_variable_element_type(var);
2870
2871 BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
2872
2873 // Force the variable to have the proper name.
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +02002874 string var_name = builtin_to_glsl(builtin, StorageClassFunction);
2875 set_name(var.self, var_name);
Chip Davisf3c09422019-02-22 12:11:17 -06002876
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +02002877 // We need to declare the variable early and at entry-point scope.
2878 entry_func.add_local_variable(var.self);
2879 vars_needing_early_declaration.push_back(var.self);
2880 bool triangles = get_execution_mode_bitset().get(ExecutionModeTriangles);
2881 string mbr_name;
Chip Davisf3c09422019-02-22 12:11:17 -06002882
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +02002883 // Add a reference to the variable type to the interface struct.
2884 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
Chip Davisf3c09422019-02-22 12:11:17 -06002885
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +02002886 const auto mark_locations = [&](const SPIRType &new_var_type) {
Chip Davisf3c09422019-02-22 12:11:17 -06002887 if (get_decoration_bitset(var.self).get(DecorationLocation))
2888 {
2889 uint32_t locn = get_decoration(var.self, DecorationLocation);
2890 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002891 mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput);
Chip Davisf3c09422019-02-22 12:11:17 -06002892 }
Chip Davis5281d992020-06-13 23:03:30 -05002893 else if (inputs_by_builtin.count(builtin))
Chip Davisf3c09422019-02-22 12:11:17 -06002894 {
Chip Davis5281d992020-06-13 23:03:30 -05002895 uint32_t locn = inputs_by_builtin[builtin].location;
Chip Davisf3c09422019-02-22 12:11:17 -06002896 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Chip Davis688c5fc2020-02-20 21:38:28 -06002897 mark_location_as_used_by_shader(locn, new_var_type, StorageClassInput);
Chip Davisf3c09422019-02-22 12:11:17 -06002898 }
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +02002899 };
2900
2901 if (triangles)
2902 {
2903 // Triangles are tricky, because we want only one member in the struct.
2904 mbr_name = "gl_TessLevel";
2905
2906 // If we already added the other one, we can skip this step.
2907 if (!added_builtin_tess_level)
2908 {
2909 uint32_t type_id = build_extended_vector_type(var_type.self, 4);
2910
2911 ib_type.member_types.push_back(type_id);
2912
2913 // Give the member a name
2914 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2915
2916 // We cannot decorate both, but the important part is that
2917 // it's marked as builtin so we can get automatic attribute assignment if needed.
2918 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
2919
2920 mark_locations(var_type);
2921 added_builtin_tess_level = true;
2922 }
2923 }
2924 else
2925 {
2926 mbr_name = var_name;
2927
2928 uint32_t type_id = build_extended_vector_type(var_type.self, builtin == BuiltInTessLevelOuter ? 4 : 2);
2929
2930 uint32_t ptr_type_id = ir.increase_bound_by(1);
2931 auto &new_var_type = set<SPIRType>(ptr_type_id, get<SPIRType>(type_id));
2932 new_var_type.pointer = true;
2933 new_var_type.pointer_depth++;
2934 new_var_type.storage = StorageClassInput;
2935 new_var_type.parent_type = type_id;
2936
2937 ib_type.member_types.push_back(type_id);
2938
2939 // Give the member a name
2940 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
2941 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
2942
2943 mark_locations(new_var_type);
2944 }
2945
2946 if (builtin == BuiltInTessLevelOuter)
2947 {
2948 entry_func.fixup_hooks_in.push_back([=]() {
2949 statement(var_name, "[0] = ", ib_var_ref, ".", mbr_name, ".x;");
2950 statement(var_name, "[1] = ", ib_var_ref, ".", mbr_name, ".y;");
2951 statement(var_name, "[2] = ", ib_var_ref, ".", mbr_name, ".z;");
2952 if (!triangles)
2953 statement(var_name, "[3] = ", ib_var_ref, ".", mbr_name, ".w;");
2954 });
2955 }
2956 else
2957 {
2958 entry_func.fixup_hooks_in.push_back([=]() {
2959 if (triangles)
2960 {
2961 statement(var_name, "[0] = ", ib_var_ref, ".", mbr_name, ".w;");
2962 }
2963 else
2964 {
2965 statement(var_name, "[0] = ", ib_var_ref, ".", mbr_name, ".x;");
2966 statement(var_name, "[1] = ", ib_var_ref, ".", mbr_name, ".y;");
2967 }
2968 });
Chip Davisf3c09422019-02-22 12:11:17 -06002969 }
2970}
2971
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02002972bool CompilerMSL::variable_storage_requires_stage_io(spv::StorageClass storage) const
2973{
2974 if (storage == StorageClassOutput)
2975 return !capture_output_to_buffer;
2976 else if (storage == StorageClassInput)
2977 return !(get_execution_model() == ExecutionModelTessellationControl && msl_options.multi_patch_workgroup);
2978 else
2979 return false;
2980}
2981
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02002982string CompilerMSL::to_tesc_invocation_id()
2983{
2984 if (msl_options.multi_patch_workgroup)
2985 {
2986 // n.b. builtin_invocation_id_id here is the dispatch global invocation ID,
2987 // not the TC invocation ID.
2988 return join(to_expression(builtin_invocation_id_id), ".x % ", get_entry_point().output_vertices);
2989 }
2990 else
2991 return builtin_to_glsl(BuiltInInvocationId, StorageClassInput);
2992}
2993
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02002994void CompilerMSL::emit_local_masked_variable(const SPIRVariable &masked_var, bool strip_array)
2995{
2996 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
2997 bool threadgroup_storage = variable_decl_is_remapped_storage(masked_var, StorageClassWorkgroup);
2998
2999 if (threadgroup_storage && msl_options.multi_patch_workgroup)
3000 {
3001 // We need one threadgroup block per patch, so fake this.
3002 entry_func.fixup_hooks_in.push_back([this, &masked_var]() {
3003 auto &type = get_variable_data_type(masked_var);
3004 add_local_variable_name(masked_var.self);
3005
3006 bool old_is_builtin = is_using_builtin_array;
3007 is_using_builtin_array = true;
3008
3009 const uint32_t max_control_points_per_patch = 32u;
3010 uint32_t max_num_instances =
3011 (max_control_points_per_patch + get_entry_point().output_vertices - 1u) /
3012 get_entry_point().output_vertices;
3013 statement("threadgroup ", type_to_glsl(type), " ",
3014 "spvStorage", to_name(masked_var.self), "[", max_num_instances, "]",
3015 type_to_array_glsl(type), ";");
3016
3017 // Assign a threadgroup slice to each PrimitiveID.
3018 // We assume here that workgroup size is rounded to 32,
3019 // since that's the maximum number of control points per patch.
3020 // We cannot size the array based on fixed dispatch parameters,
3021 // since Metal does not allow that. :(
3022 // FIXME: We will likely need an option to support passing down target workgroup size,
3023 // so we can emit appropriate size here.
3024 statement("threadgroup ", type_to_glsl(type), " ",
3025 "(&", to_name(masked_var.self), ")",
3026 type_to_array_glsl(type), " = spvStorage", to_name(masked_var.self), "[",
3027 "(", to_expression(builtin_invocation_id_id), ".x / ",
3028 get_entry_point().output_vertices, ") % ",
3029 max_num_instances, "];");
3030
3031 is_using_builtin_array = old_is_builtin;
3032 });
3033 }
3034 else
3035 {
3036 entry_func.add_local_variable(masked_var.self);
3037 }
3038
3039 if (!threadgroup_storage)
3040 {
3041 vars_needing_early_declaration.push_back(masked_var.self);
3042 }
3043 else if (masked_var.initializer)
3044 {
3045 // Cannot directly initialize threadgroup variables. Need fixup hooks.
3046 ID initializer = masked_var.initializer;
3047 if (strip_array)
3048 {
3049 entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() {
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02003050 auto invocation = to_tesc_invocation_id();
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003051 statement(to_expression(masked_var.self), "[",
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02003052 invocation, "] = ",
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003053 to_expression(initializer), "[",
Hans-Kristian Arntzen7b9a5912021-04-16 11:26:47 +02003054 invocation, "];");
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003055 });
3056 }
3057 else
3058 {
3059 entry_func.fixup_hooks_in.push_back([this, &masked_var, initializer]() {
3060 statement(to_expression(masked_var.self), " = ", to_expression(initializer), ";");
3061 });
3062 }
3063 }
3064}
3065
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003066void CompilerMSL::add_variable_to_interface_block(StorageClass storage, const string &ib_var_ref, SPIRType &ib_type,
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003067 SPIRVariable &var, InterfaceBlockMeta &meta)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003068{
3069 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003070 // Tessellation control I/O variables and tessellation evaluation per-point inputs are
3071 // usually declared as arrays. In these cases, we want to add the element type to the
3072 // interface block, since in Metal it's the interface block itself which is arrayed.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003073 auto &var_type = meta.strip_array ? get_variable_element_type(var) : get_variable_data_type(var);
Chip Davisf3c09422019-02-22 12:11:17 -06003074 bool is_builtin = is_builtin_variable(var);
3075 auto builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003076 bool is_block = has_decoration(var_type.self, DecorationBlock);
3077
3078 // If stage variables are masked out, emit them as plain variables instead.
3079 // For builtins, we query them one by one later.
Hans-Kristian Arntzena59e25d2021-04-07 12:55:26 +02003080 // IO blocks are not masked here, we need to mask them per-member instead.
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02003081 if (storage == StorageClassOutput && is_stage_output_variable_masked(var))
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003082 {
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02003083 // If we ignore an output, we must still emit it, since it might be used by app.
3084 // Instead, just emit it as early declaration.
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003085 emit_local_masked_variable(var, meta.strip_array);
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02003086 return;
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003087 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003088
3089 if (var_type.basetype == SPIRType::Struct)
3090 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003091 bool block_requires_flattening = variable_storage_requires_stage_io(storage) || is_block;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003092 bool needs_local_declaration = !is_builtin && block_requires_flattening && meta.allow_local_declaration;
Hans-Kristian Arntzena59e25d2021-04-07 12:55:26 +02003093
3094 if (needs_local_declaration)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003095 {
3096 // For I/O blocks or structs, we will need to pass the block itself around
3097 // to functions if they are used globally in leaf functions.
3098 // Rather than passing down member by member,
3099 // we unflatten I/O blocks while running the shader,
3100 // and pass the actual struct type down to leaf functions.
3101 // We then unflatten inputs, and flatten outputs in the "fixup" stages.
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003102 emit_local_masked_variable(var, meta.strip_array);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003103 }
3104
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003105 if (!block_requires_flattening)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003106 {
Chip Davis0bb6bbd2019-02-11 17:18:54 -06003107 // In Metal tessellation shaders, the interface block itself is arrayed. This makes things
3108 // very complicated, since stage-in structures in MSL don't support nested structures.
3109 // Luckily, for stage-out when capturing output, we can avoid this and just add
3110 // composite members directly, because the stage-out structure is stored to a buffer,
3111 // not returned.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003112 add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003113 }
3114 else
3115 {
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +02003116 bool masked_block = false;
3117
Chip Daviseb89c3a2019-02-03 23:58:46 -06003118 // Flatten the struct members into the interface struct
3119 for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003120 {
Chip Davisf3c09422019-02-22 12:11:17 -06003121 builtin = BuiltInMax;
3122 is_builtin = is_member_builtin(var_type, mbr_idx, &builtin);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003123 auto &mbr_type = get<SPIRType>(var_type.member_types[mbr_idx]);
3124
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003125 if (storage == StorageClassOutput && is_stage_output_block_member_masked(var, mbr_idx, meta.strip_array))
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003126 {
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02003127 if (is_block)
3128 masked_block = true;
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +02003129
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003130 // Non-builtin block output variables are just ignored, since they will still access
3131 // the block variable as-is. They're just not flattened.
Hans-Kristian Arntzena59e25d2021-04-07 12:55:26 +02003132 if (is_builtin && !meta.strip_array)
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003133 {
3134 // Emit a fake variable instead.
3135 uint32_t ids = ir.increase_bound_by(2);
3136 uint32_t ptr_type_id = ids + 0;
3137 uint32_t var_id = ids + 1;
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003138
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003139 auto ptr_type = mbr_type;
3140 ptr_type.pointer = true;
3141 ptr_type.pointer_depth++;
3142 ptr_type.parent_type = var_type.member_types[mbr_idx];
3143 ptr_type.storage = StorageClassOutput;
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003144
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003145 uint32_t initializer = 0;
3146 if (var.initializer)
3147 if (auto *c = maybe_get<SPIRConstant>(var.initializer))
3148 initializer = c->subconstants[mbr_idx];
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003149
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02003150 set<SPIRType>(ptr_type_id, ptr_type);
3151 set<SPIRVariable>(var_id, ptr_type_id, StorageClassOutput, initializer);
3152 entry_func.add_local_variable(var_id);
3153 vars_needing_early_declaration.push_back(var_id);
3154 set_name(var_id, builtin_to_glsl(builtin, StorageClassOutput));
3155 set_decoration(var_id, DecorationBuiltIn, builtin);
3156 }
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +01003157 }
3158 else if (!is_builtin || has_active_builtin(builtin, storage))
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003159 {
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003160 bool is_composite_type = is_matrix(mbr_type) || is_array(mbr_type);
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01003161 bool attribute_load_store =
3162 storage == StorageClassInput && get_execution_model() != ExecutionModelFragment;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003163 bool storage_is_stage_io = variable_storage_requires_stage_io(storage);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003164
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02003165 // Clip/CullDistance always need to be declared as user attributes.
3166 if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003167 is_builtin = false;
3168
3169 if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type)
Chip Daviseb89c3a2019-02-03 23:58:46 -06003170 {
3171 add_composite_member_variable_to_interface_block(storage, ib_var_ref, ib_type, var, mbr_idx,
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003172 meta);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003173 }
3174 else
3175 {
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01003176 add_plain_member_variable_to_interface_block(storage, ib_var_ref, ib_type, var, mbr_idx, meta);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003177 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003178 }
3179 }
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +02003180
3181 // If we're redirecting a block, we might still need to access the original block
3182 // variable if we're masking some members.
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02003183 if (masked_block && !needs_local_declaration &&
3184 (!is_builtin_variable(var) || get_execution_model() == ExecutionModelTessellationControl))
3185 {
3186 if (is_builtin_variable(var))
3187 {
3188 // Ensure correct names for the block members if we're actually going to
3189 // declare gl_PerVertex.
3190 for (uint32_t mbr_idx = 0; mbr_idx < uint32_t(var_type.member_types.size()); mbr_idx++)
3191 {
3192 set_member_name(var_type.self, mbr_idx, builtin_to_glsl(
3193 BuiltIn(get_member_decoration(var_type.self, mbr_idx, DecorationBuiltIn)),
3194 StorageClassOutput));
3195 }
3196
3197 set_name(var_type.self, "gl_PerVertex");
3198 set_name(var.self, "gl_out_masked");
3199 stage_out_masked_builtin_type_id = var_type.self;
3200 }
Hans-Kristian Arntzen23da4452021-04-14 13:13:13 +02003201 emit_local_masked_variable(var, meta.strip_array);
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02003202 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003203 }
3204 }
Chip Davisf3c09422019-02-22 12:11:17 -06003205 else if (get_execution_model() == ExecutionModelTessellationEvaluation && storage == StorageClassInput &&
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003206 !meta.strip_array && is_builtin && (builtin == BuiltInTessLevelOuter || builtin == BuiltInTessLevelInner))
Chip Davisf3c09422019-02-22 12:11:17 -06003207 {
3208 add_tess_level_input_to_interface_block(ib_var_ref, ib_type, var);
3209 }
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003210 else if (var_type.basetype == SPIRType::Boolean || var_type.basetype == SPIRType::Char ||
Hans-Kristian Arntzen1a38fec2021-01-04 12:07:48 +01003211 type_is_integral(var_type) || type_is_floating_point(var_type))
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003212 {
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003213 if (!is_builtin || has_active_builtin(builtin, storage))
3214 {
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003215 bool is_composite_type = is_matrix(var_type) || is_array(var_type);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003216 bool storage_is_stage_io = variable_storage_requires_stage_io(storage);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003217 bool attribute_load_store = storage == StorageClassInput && get_execution_model() != ExecutionModelFragment;
3218
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02003219 // Clip/CullDistance always needs to be declared as user attributes.
3220 if (builtin == BuiltInClipDistance || builtin == BuiltInCullDistance)
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003221 is_builtin = false;
3222
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003223 // MSL does not allow matrices or arrays in input or output variables, so need to handle it specially.
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003224 if ((!is_builtin || attribute_load_store) && storage_is_stage_io && is_composite_type)
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003225 {
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003226 add_composite_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003227 }
3228 else
3229 {
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003230 add_plain_variable_to_interface_block(storage, ib_var_ref, ib_type, var, meta);
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01003231 }
3232 }
3233 }
3234}
3235
Chip Daviseb89c3a2019-02-03 23:58:46 -06003236// Fix up the mapping of variables to interface member indices, which is used to compile access chains
3237// for per-vertex variables in a tessellation control shader.
3238void CompilerMSL::fix_up_interface_member_indices(StorageClass storage, uint32_t ib_type_id)
3239{
Chip Davisaca9b682020-11-02 20:56:46 -06003240 // Only needed for tessellation shaders and pull-model interpolants.
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02003241 // Need to redirect interface indices back to variables themselves.
3242 // For structs, each member of the struct need a separate instance.
Chip Davise75add42019-02-05 18:13:26 -06003243 if (get_execution_model() != ExecutionModelTessellationControl &&
Chip Davisaca9b682020-11-02 20:56:46 -06003244 !(get_execution_model() == ExecutionModelTessellationEvaluation && storage == StorageClassInput) &&
3245 !(get_execution_model() == ExecutionModelFragment && storage == StorageClassInput &&
3246 !pull_model_inputs.empty()))
Chip Daviseb89c3a2019-02-03 23:58:46 -06003247 return;
3248
Hans-Kristian Arntzenac8d3352019-10-26 20:30:24 +02003249 auto mbr_cnt = uint32_t(ir.meta[ib_type_id].members.size());
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02003250 for (uint32_t i = 0; i < mbr_cnt; i++)
Chip Daviseb89c3a2019-02-03 23:58:46 -06003251 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02003252 uint32_t var_id = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceOrigID);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003253 if (!var_id)
3254 continue;
3255 auto &var = get<SPIRVariable>(var_id);
3256
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02003257 auto &type = get_variable_element_type(var);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003258
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003259 bool flatten_composites = variable_storage_requires_stage_io(var.storage);
3260 bool is_block = has_decoration(type.self, DecorationBlock);
3261
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003262 uint32_t mbr_idx = uint32_t(-1);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003263 if (type.basetype == SPIRType::Struct && (flatten_composites || is_block))
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003264 mbr_idx = get_extended_member_decoration(ib_type_id, i, SPIRVCrossDecorationInterfaceMemberIndex);
3265
3266 if (mbr_idx != uint32_t(-1))
3267 {
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02003268 // Only set the lowest InterfaceMemberIndex for each variable member.
3269 // IB struct members will be emitted in-order w.r.t. interface member index.
3270 if (!has_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex))
3271 set_extended_member_decoration(var_id, mbr_idx, SPIRVCrossDecorationInterfaceMemberIndex, i);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003272 }
3273 else
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02003274 {
3275 // Only set the lowest InterfaceMemberIndex for each variable.
3276 // IB struct members will be emitted in-order w.r.t. interface member index.
3277 if (!has_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex))
3278 set_extended_decoration(var_id, SPIRVCrossDecorationInterfaceMemberIndex, i);
3279 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003280 }
3281}
3282
Bill Hollingse27a5f72017-01-01 14:43:20 -05003283// Add an interface structure for the type of storage, which is either StorageClassInput or StorageClassOutput.
Bill Hollings103aabf2016-04-06 17:42:27 -04003284// Returns the ID of the newly added variable, or zero if no variable was added.
Chip Daviseb89c3a2019-02-03 23:58:46 -06003285uint32_t CompilerMSL::add_interface_block(StorageClass storage, bool patch)
Bill Hollings103aabf2016-04-06 17:42:27 -04003286{
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003287 // Accumulate the variables that should appear in the interface struct.
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02003288 SmallVector<SPIRVariable *> vars;
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003289 bool incl_builtins = storage == StorageClassOutput || is_tessellation_shader();
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +02003290 bool has_seen_barycentric = false;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01003291
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003292 InterfaceBlockMeta meta;
3293
3294 // Varying interfaces between stages which use "user()" attribute can be dealt with
3295 // without explicit packing and unpacking of components. For any variables which link against the runtime
3296 // in some way (vertex attributes, fragment output, etc), we'll need to deal with it somehow.
3297 bool pack_components =
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01003298 (storage == StorageClassInput && get_execution_model() == ExecutionModelVertex) ||
3299 (storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment) ||
3300 (storage == StorageClassOutput && get_execution_model() == ExecutionModelVertex && capture_output_to_buffer);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003301
Chip Daviseb89c3a2019-02-03 23:58:46 -06003302 ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003303 if (var.storage != storage)
3304 return;
3305
Hans-Kristian Arntzen2fb9aa22019-01-11 09:29:28 +01003306 auto &type = this->get<SPIRType>(var.basetype);
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003307
3308 bool is_builtin = is_builtin_variable(var);
Hans-Kristian Arntzena1593342021-04-14 14:28:27 +02003309 bool is_block = has_decoration(type.self, DecorationBlock);
3310
3311 auto bi_type = BuiltInMax;
3312 bool builtin_is_gl_in_out = false;
3313 if (is_builtin && !is_block)
3314 {
3315 bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn));
3316 builtin_is_gl_in_out = bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
3317 bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance;
3318 }
3319
3320 if (is_builtin && is_block)
3321 builtin_is_gl_in_out = true;
3322
Chip Davisb29f83c2020-04-10 01:13:33 -05003323 uint32_t location = get_decoration(var_id, DecorationLocation);
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003324
Hans-Kristian Arntzena1593342021-04-14 14:28:27 +02003325 bool builtin_is_stage_in_out = builtin_is_gl_in_out ||
3326 bi_type == BuiltInLayer || bi_type == BuiltInViewportIndex ||
3327 bi_type == BuiltInBaryCoordNV || bi_type == BuiltInBaryCoordNoPerspNV ||
3328 bi_type == BuiltInFragDepth ||
3329 bi_type == BuiltInFragStencilRefEXT || bi_type == BuiltInSampleMask;
3330
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003331 // These builtins are part of the stage in/out structs.
3332 bool is_interface_block_builtin =
Hans-Kristian Arntzena1593342021-04-14 14:28:27 +02003333 builtin_is_stage_in_out ||
3334 (get_execution_model() == ExecutionModelTessellationEvaluation &&
3335 (bi_type == BuiltInTessLevelOuter || bi_type == BuiltInTessLevelInner));
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003336
3337 bool is_active = interface_variable_exists_in_entry_point(var.self);
3338 if (is_builtin && is_active)
3339 {
3340 // Only emit the builtin if it's active in this entry point. Interface variable list might lie.
Hans-Kristian Arntzena1593342021-04-14 14:28:27 +02003341 if (is_block)
3342 {
3343 // If any builtin is active, the block is active.
3344 uint32_t mbr_cnt = uint32_t(type.member_types.size());
3345 for (uint32_t i = 0; !is_active && i < mbr_cnt; i++)
3346 is_active = has_active_builtin(BuiltIn(get_member_decoration(type.self, i, DecorationBuiltIn)), storage);
3347 }
3348 else
3349 {
3350 is_active = has_active_builtin(bi_type, storage);
3351 }
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003352 }
3353
3354 bool filter_patch_decoration = (has_decoration(var_id, DecorationPatch) || is_patch_block(type)) == patch;
3355
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +02003356 bool hidden = is_hidden_variable(var, incl_builtins);
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003357
3358 // ClipDistance is never hidden, we need to emulate it when used as an input.
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +02003359 if (bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance)
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +01003360 hidden = false;
3361
Chip Davisb29f83c2020-04-10 01:13:33 -05003362 // It's not enough to simply avoid marking fragment outputs if the pipeline won't
3363 // accept them. We can't put them in the struct at all, or otherwise the compiler
3364 // complains that the outputs weren't explicitly marked.
Bill Hollings248e9ae2021-11-12 14:17:00 -05003365 // Frag depth and stencil outputs are incompatible with explicit early fragment tests.
3366 // In GLSL, depth and stencil outputs are just ignored when explicit early fragment tests are required.
3367 // In Metal, it's a compilation error, so we need to exclude them from the output struct.
Chip Davis495e48d2020-04-15 12:13:25 -05003368 if (get_execution_model() == ExecutionModelFragment && storage == StorageClassOutput && !patch &&
Bill Hollings248e9ae2021-11-12 14:17:00 -05003369 ((is_builtin && ((bi_type == BuiltInFragDepth && (!msl_options.enable_frag_depth_builtin || uses_explicit_early_fragment_test())) ||
3370 (bi_type == BuiltInFragStencilRefEXT && (!msl_options.enable_frag_stencil_ref_builtin || uses_explicit_early_fragment_test())))) ||
Chip Davisb29f83c2020-04-10 01:13:33 -05003371 (!is_builtin && !(msl_options.enable_frag_output_mask & (1 << location)))))
3372 {
3373 hidden = true;
3374 disabled_frag_outputs.push_back(var_id);
Bill Hollings248e9ae2021-11-12 14:17:00 -05003375 // If a builtin, force it to have the proper name, and mark it as not part of the output struct.
Chip Davis96f70082020-04-15 19:22:16 -05003376 if (is_builtin)
Bill Hollings248e9ae2021-11-12 14:17:00 -05003377 {
Chip Davis96f70082020-04-15 19:22:16 -05003378 set_name(var_id, builtin_to_glsl(bi_type, StorageClassFunction));
Bill Hollings248e9ae2021-11-12 14:17:00 -05003379 mask_stage_output_by_builtin(bi_type);
3380 }
Chip Davisb29f83c2020-04-10 01:13:33 -05003381 }
3382
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +02003383 // Barycentric inputs must be emitted in stage-in, because they can have interpolation arguments.
3384 if (is_active && (bi_type == BuiltInBaryCoordNV || bi_type == BuiltInBaryCoordNoPerspNV))
3385 {
3386 if (has_seen_barycentric)
3387 SPIRV_CROSS_THROW("Cannot declare both BaryCoordNV and BaryCoordNoPerspNV in same shader in MSL.");
3388 has_seen_barycentric = true;
3389 hidden = false;
3390 }
3391
3392 if (is_active && !hidden && type.pointer && filter_patch_decoration &&
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +02003393 (!is_builtin || is_interface_block_builtin))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003394 {
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01003395 vars.push_back(&var);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003396
Hans-Kristian Arntzen88715022020-01-07 16:49:19 +01003397 if (!is_builtin)
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003398 {
3399 // Need to deal specially with DecorationComponent.
3400 // Multiple variables can alias the same Location, and try to make sure each location is declared only once.
3401 // We will swizzle data in and out to make this work.
Hans-Kristian Arntzen88715022020-01-07 16:49:19 +01003402 // This is only relevant for vertex inputs and fragment outputs.
3403 // Technically tessellation as well, but it is too complicated to support.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003404 uint32_t component = get_decoration(var_id, DecorationComponent);
3405 if (component != 0)
3406 {
Hans-Kristian Arntzen88715022020-01-07 16:49:19 +01003407 if (is_tessellation_shader())
3408 SPIRV_CROSS_THROW("Component decoration is not supported in tessellation shaders.");
3409 else if (pack_components)
3410 {
Hans-Kristian Arntzena64ddcd2021-05-21 12:31:33 +02003411 uint32_t array_size = 1;
3412 if (!type.array.empty())
3413 array_size = to_array_size_literal(type);
3414
3415 for (uint32_t location_offset = 0; location_offset < array_size; location_offset++)
3416 {
3417 auto &location_meta = meta.location_meta[location + location_offset];
3418 location_meta.num_components = std::max(location_meta.num_components, component + type.vecsize);
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02003419
3420 // For variables sharing location, decorations and base type must match.
3421 location_meta.base_type_id = type.self;
3422 location_meta.flat = has_decoration(var.self, DecorationFlat);
3423 location_meta.noperspective = has_decoration(var.self, DecorationNoPerspective);
3424 location_meta.centroid = has_decoration(var.self, DecorationCentroid);
3425 location_meta.sample = has_decoration(var.self, DecorationSample);
Hans-Kristian Arntzena64ddcd2021-05-21 12:31:33 +02003426 }
Hans-Kristian Arntzen88715022020-01-07 16:49:19 +01003427 }
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003428 }
3429 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003430 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01003431 });
Bill Hollings103aabf2016-04-06 17:42:27 -04003432
Chip Davise75add42019-02-05 18:13:26 -06003433 // If no variables qualify, leave.
3434 // For patch input in a tessellation evaluation shader, the per-vertex stage inputs
3435 // are included in a special patch control point array.
3436 if (vars.empty() && !(storage == StorageClassInput && patch && stage_in_var_id))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003437 return 0;
Bill Hollings103aabf2016-04-06 17:42:27 -04003438
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003439 // Add a new typed variable for this interface structure.
3440 // The initializer expression is allocated here, but populated when the function
3441 // declaraion is emitted, because it is cleared after each compilation pass.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02003442 uint32_t next_id = ir.increase_bound_by(3);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003443 uint32_t ib_type_id = next_id++;
3444 auto &ib_type = set<SPIRType>(ib_type_id);
3445 ib_type.basetype = SPIRType::Struct;
3446 ib_type.storage = storage;
Bill Hollings32ae2ec2016-12-18 18:48:15 -05003447 set_decoration(ib_type_id, DecorationBlock);
Bill Hollings103aabf2016-04-06 17:42:27 -04003448
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003449 uint32_t ib_var_id = next_id++;
3450 auto &var = set<SPIRVariable>(ib_var_id, ib_type_id, storage, 0);
3451 var.initializer = next_id++;
Bill Hollings103aabf2016-04-06 17:42:27 -04003452
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003453 string ib_var_ref;
Chip Daviseb89c3a2019-02-03 23:58:46 -06003454 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Bill Hollingse27a5f72017-01-01 14:43:20 -05003455 switch (storage)
Bill Hollingsaca1b552016-12-04 12:32:58 -05003456 {
Bill Hollingse27a5f72017-01-01 14:43:20 -05003457 case StorageClassInput:
Chip Davise75add42019-02-05 18:13:26 -06003458 ib_var_ref = patch ? patch_stage_in_var_name : stage_in_var_name;
Chip Daviseb89c3a2019-02-03 23:58:46 -06003459 if (get_execution_model() == ExecutionModelTessellationControl)
3460 {
Chip Davis688c5fc2020-02-20 21:38:28 -06003461 // Add a hook to populate the shared workgroup memory containing the gl_in array.
Chip Daviseb89c3a2019-02-03 23:58:46 -06003462 entry_func.fixup_hooks_in.push_back([=]() {
Chip Davis688c5fc2020-02-20 21:38:28 -06003463 // Can't use PatchVertices, PrimitiveId, or InvocationId yet; the hooks for those may not have run yet.
3464 if (msl_options.multi_patch_workgroup)
3465 {
3466 // n.b. builtin_invocation_id_id here is the dispatch global invocation ID,
3467 // not the TC invocation ID.
3468 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_in = &",
3469 input_buffer_var_name, "[min(", to_expression(builtin_invocation_id_id), ".x / ",
3470 get_entry_point().output_vertices,
Hans-Kristian Arntzen95993f72020-08-24 11:02:49 +02003471 ", spvIndirectParams[1] - 1) * spvIndirectParams[0]];");
Chip Davis688c5fc2020-02-20 21:38:28 -06003472 }
3473 else
3474 {
3475 // It's safe to use InvocationId here because it's directly mapped to a
3476 // Metal builtin, and therefore doesn't need a hook.
3477 statement("if (", to_expression(builtin_invocation_id_id), " < spvIndirectParams[0])");
3478 statement(" ", input_wg_var_name, "[", to_expression(builtin_invocation_id_id),
3479 "] = ", ib_var_ref, ";");
3480 statement("threadgroup_barrier(mem_flags::mem_threadgroup);");
3481 statement("if (", to_expression(builtin_invocation_id_id),
3482 " >= ", get_entry_point().output_vertices, ")");
3483 statement(" return;");
3484 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003485 });
3486 }
Bill Hollingse27a5f72017-01-01 14:43:20 -05003487 break;
Bill Hollingsaca1b552016-12-04 12:32:58 -05003488
Bill Hollingse27a5f72017-01-01 14:43:20 -05003489 case StorageClassOutput:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003490 {
Chip Daviseb89c3a2019-02-03 23:58:46 -06003491 ib_var_ref = patch ? patch_stage_out_var_name : stage_out_var_name;
Bill Hollings103aabf2016-04-06 17:42:27 -04003492
Bill Hollingsac238b82018-07-26 00:50:33 -04003493 // Add the output interface struct as a local variable to the entry function.
3494 // If the entry point should return the output struct, set the entry function
3495 // to return the output interface struct, otherwise to return nothing.
Bill Hollings2a150f52021-09-14 14:58:42 -04003496 // Watch out for the rare case where the terminator of the last entry point block is a
3497 // Kill, instead of a Return. Based on SPIR-V's block-domination rules, we assume that
3498 // any block that has a Kill will also have a terminating Return, except the last block.
Bill Hollingsac238b82018-07-26 00:50:33 -04003499 // Indicate the output var requires early initialization.
Bill Hollings0d6202e2018-07-26 16:40:32 -04003500 bool ep_should_return_output = !get_is_rasterization_disabled();
Bill Hollingsac238b82018-07-26 00:50:33 -04003501 uint32_t rtn_id = ep_should_return_output ? ib_var_id : 0;
Chip Davisc51e5b72019-01-08 16:33:32 -06003502 if (!capture_output_to_buffer)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003503 {
Chip Davisc51e5b72019-01-08 16:33:32 -06003504 entry_func.add_local_variable(ib_var_id);
3505 for (auto &blk_id : entry_func.blocks)
3506 {
3507 auto &blk = get<SPIRBlock>(blk_id);
Bill Hollings35e92e62021-09-12 16:28:21 -04003508 if (blk.terminator == SPIRBlock::Return || (blk.terminator == SPIRBlock::Kill && blk_id == entry_func.blocks.back()))
Chip Davisc51e5b72019-01-08 16:33:32 -06003509 blk.return_value = rtn_id;
3510 }
3511 vars_needing_early_declaration.push_back(ib_var_id);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003512 }
Chip Davisc51e5b72019-01-08 16:33:32 -06003513 else
3514 {
Chip Daviseb89c3a2019-02-03 23:58:46 -06003515 switch (get_execution_model())
3516 {
3517 case ExecutionModelVertex:
Chip Davise75add42019-02-05 18:13:26 -06003518 case ExecutionModelTessellationEvaluation:
Chip Daviseb89c3a2019-02-03 23:58:46 -06003519 // Instead of declaring a struct variable to hold the output and then
3520 // copying that to the output buffer, we'll declare the output variable
3521 // as a reference to the final output element in the buffer. Then we can
3522 // avoid the extra copy.
3523 entry_func.fixup_hooks_in.push_back([=]() {
3524 if (stage_out_var_id)
3525 {
3526 // The first member of the indirect buffer is always the number of vertices
3527 // to draw.
Lukas Hermanns50ac6862019-09-18 14:03:54 -04003528 // We zero-base the InstanceID & VertexID variables for HLSL emulation elsewhere, so don't do it twice
Chip Davis688c5fc2020-02-20 21:38:28 -06003529 if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
3530 {
3531 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
3532 " = ", output_buffer_var_name, "[", to_expression(builtin_invocation_id_id),
3533 ".y * ", to_expression(builtin_stage_input_size_id), ".x + ",
3534 to_expression(builtin_invocation_id_id), ".x];");
3535 }
3536 else if (msl_options.enable_base_index_zero)
Mark Satterthwaitede6441a2019-08-14 10:50:36 -04003537 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04003538 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
3539 " = ", output_buffer_var_name, "[", to_expression(builtin_instance_idx_id),
3540 " * spvIndirectParams[0] + ", to_expression(builtin_vertex_idx_id), "];");
Mark Satterthwaitede6441a2019-08-14 10:50:36 -04003541 }
3542 else
3543 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04003544 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
3545 " = ", output_buffer_var_name, "[(", to_expression(builtin_instance_idx_id),
3546 " - ", to_expression(builtin_base_instance_id), ") * spvIndirectParams[0] + ",
3547 to_expression(builtin_vertex_idx_id), " - ",
3548 to_expression(builtin_base_vertex_id), "];");
Mark Satterthwaitede6441a2019-08-14 10:50:36 -04003549 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003550 }
3551 });
3552 break;
3553 case ExecutionModelTessellationControl:
Chip Davis688c5fc2020-02-20 21:38:28 -06003554 if (msl_options.multi_patch_workgroup)
3555 {
3556 // We cannot use PrimitiveId here, because the hook may not have run yet.
3557 if (patch)
3558 {
3559 entry_func.fixup_hooks_in.push_back([=]() {
3560 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
3561 " = ", patch_output_buffer_var_name, "[", to_expression(builtin_invocation_id_id),
3562 ".x / ", get_entry_point().output_vertices, "];");
3563 });
3564 }
3565 else
3566 {
3567 entry_func.fixup_hooks_in.push_back([=]() {
3568 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &",
3569 output_buffer_var_name, "[", to_expression(builtin_invocation_id_id), ".x - ",
3570 to_expression(builtin_invocation_id_id), ".x % ",
3571 get_entry_point().output_vertices, "];");
3572 });
3573 }
3574 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003575 else
Chip Davis688c5fc2020-02-20 21:38:28 -06003576 {
3577 if (patch)
3578 {
3579 entry_func.fixup_hooks_in.push_back([=]() {
3580 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "& ", ib_var_ref,
3581 " = ", patch_output_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
3582 "];");
3583 });
3584 }
3585 else
3586 {
3587 entry_func.fixup_hooks_in.push_back([=]() {
3588 statement("device ", to_name(ir.default_entry_point), "_", ib_var_ref, "* gl_out = &",
3589 output_buffer_var_name, "[", to_expression(builtin_primitive_id_id), " * ",
3590 get_entry_point().output_vertices, "];");
3591 });
3592 }
3593 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003594 break;
3595 default:
3596 break;
3597 }
Chip Davisc51e5b72019-01-08 16:33:32 -06003598 }
Bill Hollingse27a5f72017-01-01 14:43:20 -05003599 break;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003600 }
Robert Konrada778c362017-01-15 16:39:03 +01003601
Bill Hollingse27a5f72017-01-01 14:43:20 -05003602 default:
3603 break;
Bill Hollings6ddd80e2016-04-08 15:12:40 -04003604 }
Bill Hollings103aabf2016-04-06 17:42:27 -04003605
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02003606 set_name(ib_type_id, to_name(ir.default_entry_point) + "_" + ib_var_ref);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003607 set_name(ib_var_id, ib_var_ref);
Bill Hollings103aabf2016-04-06 17:42:27 -04003608
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +02003609 for (auto *p_var : vars)
Chip Daviseb89c3a2019-02-03 23:58:46 -06003610 {
Chip Davise75add42019-02-05 18:13:26 -06003611 bool strip_array =
3612 (get_execution_model() == ExecutionModelTessellationControl ||
3613 (get_execution_model() == ExecutionModelTessellationEvaluation && storage == StorageClassInput)) &&
3614 !patch;
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003615
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003616 // Fixing up flattened stores in TESC is impossible since the memory is group shared either via
3617 // device (not masked) or threadgroup (masked) storage classes and it's race condition city.
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003618 meta.strip_array = strip_array;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003619 meta.allow_local_declaration = !strip_array && !(get_execution_model() == ExecutionModelTessellationControl &&
3620 storage == StorageClassOutput);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003621 add_variable_to_interface_block(storage, ib_var_ref, ib_type, *p_var, meta);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003622 }
Bill Hollings103aabf2016-04-06 17:42:27 -04003623
Chip Davis688c5fc2020-02-20 21:38:28 -06003624 if (get_execution_model() == ExecutionModelTessellationControl && msl_options.multi_patch_workgroup &&
3625 storage == StorageClassInput)
3626 {
3627 // For tessellation control inputs, add all outputs from the vertex shader to ensure
3628 // the struct containing them is the correct size and layout.
3629 for (auto &input : inputs_by_location)
3630 {
Bill Hollings548a23d2021-09-20 17:57:11 -04003631 if (location_inputs_in_use.count(input.first.location) != 0)
Chip Davis688c5fc2020-02-20 21:38:28 -06003632 continue;
3633
3634 // Create a fake variable to put at the location.
3635 uint32_t offset = ir.increase_bound_by(4);
3636 uint32_t type_id = offset;
3637 uint32_t array_type_id = offset + 1;
3638 uint32_t ptr_type_id = offset + 2;
3639 uint32_t var_id = offset + 3;
3640
3641 SPIRType type;
3642 switch (input.second.format)
3643 {
3644 case MSL_SHADER_INPUT_FORMAT_UINT16:
3645 case MSL_SHADER_INPUT_FORMAT_ANY16:
3646 type.basetype = SPIRType::UShort;
3647 type.width = 16;
3648 break;
3649 case MSL_SHADER_INPUT_FORMAT_ANY32:
3650 default:
3651 type.basetype = SPIRType::UInt;
3652 type.width = 32;
3653 break;
3654 }
3655 type.vecsize = input.second.vecsize;
3656 set<SPIRType>(type_id, type);
3657
3658 type.array.push_back(0);
3659 type.array_size_literal.push_back(true);
3660 type.parent_type = type_id;
3661 set<SPIRType>(array_type_id, type);
3662
3663 type.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01003664 type.pointer_depth++;
Chip Davis688c5fc2020-02-20 21:38:28 -06003665 type.parent_type = array_type_id;
3666 type.storage = storage;
3667 auto &ptr_type = set<SPIRType>(ptr_type_id, type);
3668 ptr_type.self = array_type_id;
3669
3670 auto &fake_var = set<SPIRVariable>(var_id, ptr_type_id, storage);
Bill Hollings548a23d2021-09-20 17:57:11 -04003671 set_decoration(var_id, DecorationLocation, input.first.location);
3672 if (input.first.component)
3673 set_decoration(var_id, DecorationComponent, input.first.component);
3674
Chip Davis688c5fc2020-02-20 21:38:28 -06003675 meta.strip_array = true;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003676 meta.allow_local_declaration = false;
Chip Davis688c5fc2020-02-20 21:38:28 -06003677 add_variable_to_interface_block(storage, ib_var_ref, ib_type, fake_var, meta);
3678 }
3679 }
3680
Hans-Kristian Arntzen99ae0d32021-05-21 13:03:05 +02003681 // When multiple variables need to access same location,
3682 // unroll locations one by one and we will flatten output or input as necessary.
3683 for (auto &loc : meta.location_meta)
3684 {
3685 uint32_t location = loc.first;
3686 auto &location_meta = loc.second;
3687
3688 uint32_t ib_mbr_idx = uint32_t(ib_type.member_types.size());
3689 uint32_t type_id = build_extended_vector_type(location_meta.base_type_id, location_meta.num_components);
3690 ib_type.member_types.push_back(type_id);
3691
3692 set_member_name(ib_type.self, ib_mbr_idx, join("m_location_", location));
3693 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, location);
3694 mark_location_as_used_by_shader(location, get<SPIRType>(type_id), storage);
3695
3696 if (location_meta.flat)
3697 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationFlat);
3698 if (location_meta.noperspective)
3699 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationNoPerspective);
3700 if (location_meta.centroid)
3701 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationCentroid);
3702 if (location_meta.sample)
3703 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationSample);
3704 }
3705
Bill Hollingsf591bc02017-06-30 19:10:46 -04003706 // Sort the members of the structure by their locations.
Hans-Kristian Arntzen9a144bb2021-03-26 11:00:35 +01003707 MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::LocationThenBuiltInType);
Hans-Kristian Arntzend0cc4fe2017-01-28 08:58:25 +01003708 member_sorter.sort();
Robert Konrada778c362017-01-15 16:39:03 +01003709
Chip Daviseb89c3a2019-02-03 23:58:46 -06003710 // The member indices were saved to the original variables, but after the members
3711 // were sorted, those indices are now likely incorrect. Fix those up now.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02003712 fix_up_interface_member_indices(storage, ib_type_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003713
Chip Davise75add42019-02-05 18:13:26 -06003714 // For patch inputs, add one more member, holding the array of control point data.
3715 if (get_execution_model() == ExecutionModelTessellationEvaluation && storage == StorageClassInput && patch &&
3716 stage_in_var_id)
3717 {
3718 uint32_t pcp_type_id = ir.increase_bound_by(1);
3719 auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type);
3720 pcp_type.basetype = SPIRType::ControlPointArray;
3721 pcp_type.parent_type = pcp_type.type_alias = get_stage_in_struct_type().self;
3722 pcp_type.storage = storage;
3723 ir.meta[pcp_type_id] = ir.meta[ib_type.self];
Chip Davis7042cb92019-02-21 15:11:45 -06003724 uint32_t mbr_idx = uint32_t(ib_type.member_types.size());
Chip Davise75add42019-02-05 18:13:26 -06003725 ib_type.member_types.push_back(pcp_type_id);
3726 set_member_name(ib_type.self, mbr_idx, "gl_in");
3727 }
3728
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02003729 return ib_var_id;
Bill Hollings103aabf2016-04-06 17:42:27 -04003730}
3731
Chip Daviseb89c3a2019-02-03 23:58:46 -06003732uint32_t CompilerMSL::add_interface_block_pointer(uint32_t ib_var_id, StorageClass storage)
3733{
3734 if (!ib_var_id)
3735 return 0;
3736
Chip Davise75add42019-02-05 18:13:26 -06003737 uint32_t ib_ptr_var_id;
Chip Daviseb89c3a2019-02-03 23:58:46 -06003738 uint32_t next_id = ir.increase_bound_by(3);
Chip Daviseb89c3a2019-02-03 23:58:46 -06003739 auto &ib_type = expression_type(ib_var_id);
Chip Davise75add42019-02-05 18:13:26 -06003740 if (get_execution_model() == ExecutionModelTessellationControl)
3741 {
3742 // Tessellation control per-vertex I/O is presented as an array, so we must
3743 // do the same with our struct here.
3744 uint32_t ib_ptr_type_id = next_id++;
3745 auto &ib_ptr_type = set<SPIRType>(ib_ptr_type_id, ib_type);
3746 ib_ptr_type.parent_type = ib_ptr_type.type_alias = ib_type.self;
3747 ib_ptr_type.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01003748 ib_ptr_type.pointer_depth++;
Chip Davis688c5fc2020-02-20 21:38:28 -06003749 ib_ptr_type.storage =
3750 storage == StorageClassInput ?
3751 (msl_options.multi_patch_workgroup ? StorageClassStorageBuffer : StorageClassWorkgroup) :
3752 StorageClassStorageBuffer;
Chip Davise75add42019-02-05 18:13:26 -06003753 ir.meta[ib_ptr_type_id] = ir.meta[ib_type.self];
3754 // To ensure that get_variable_data_type() doesn't strip off the pointer,
3755 // which we need, use another pointer.
3756 uint32_t ib_ptr_ptr_type_id = next_id++;
3757 auto &ib_ptr_ptr_type = set<SPIRType>(ib_ptr_ptr_type_id, ib_ptr_type);
3758 ib_ptr_ptr_type.parent_type = ib_ptr_type_id;
3759 ib_ptr_ptr_type.type_alias = ib_type.self;
3760 ib_ptr_ptr_type.storage = StorageClassFunction;
3761 ir.meta[ib_ptr_ptr_type_id] = ir.meta[ib_type.self];
Chip Daviseb89c3a2019-02-03 23:58:46 -06003762
Chip Davise75add42019-02-05 18:13:26 -06003763 ib_ptr_var_id = next_id;
3764 set<SPIRVariable>(ib_ptr_var_id, ib_ptr_ptr_type_id, StorageClassFunction, 0);
Chip Davis688c5fc2020-02-20 21:38:28 -06003765 set_name(ib_ptr_var_id, storage == StorageClassInput ? "gl_in" : "gl_out");
Chip Davise75add42019-02-05 18:13:26 -06003766 }
3767 else
3768 {
3769 // Tessellation evaluation per-vertex inputs are also presented as arrays.
3770 // But, in Metal, this array uses a very special type, 'patch_control_point<T>',
3771 // which is a container that can be used to access the control point data.
3772 // To represent this, a special 'ControlPointArray' type has been added to the
3773 // SPIRV-Cross type system. It should only be generated by and seen in the MSL
3774 // backend (i.e. this one).
3775 uint32_t pcp_type_id = next_id++;
3776 auto &pcp_type = set<SPIRType>(pcp_type_id, ib_type);
3777 pcp_type.basetype = SPIRType::ControlPointArray;
3778 pcp_type.parent_type = pcp_type.type_alias = ib_type.self;
3779 pcp_type.storage = storage;
3780 ir.meta[pcp_type_id] = ir.meta[ib_type.self];
3781
3782 ib_ptr_var_id = next_id;
3783 set<SPIRVariable>(ib_ptr_var_id, pcp_type_id, storage, 0);
3784 set_name(ib_ptr_var_id, "gl_in");
3785 ir.meta[ib_ptr_var_id].decoration.qualified_alias = join(patch_stage_in_var_name, ".gl_in");
3786 }
Chip Daviseb89c3a2019-02-03 23:58:46 -06003787 return ib_ptr_var_id;
3788}
3789
Bill Hollings2964e322018-02-13 14:44:40 -05003790// Ensure that the type is compatible with the builtin.
3791// If it is, simply return the given type ID.
3792// Otherwise, create a new type, and return it's ID.
3793uint32_t CompilerMSL::ensure_correct_builtin_type(uint32_t type_id, BuiltIn builtin)
3794{
3795 auto &type = get<SPIRType>(type_id);
3796
Chip Davis0e9ad142018-09-12 18:00:17 -05003797 if ((builtin == BuiltInSampleMask && is_array(type)) ||
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +02003798 ((builtin == BuiltInLayer || builtin == BuiltInViewportIndex || builtin == BuiltInFragStencilRefEXT) &&
3799 type.basetype != SPIRType::UInt))
Bill Hollings2964e322018-02-13 14:44:40 -05003800 {
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02003801 uint32_t next_id = ir.increase_bound_by(type.pointer ? 2 : 1);
Bill Hollings2964e322018-02-13 14:44:40 -05003802 uint32_t base_type_id = next_id++;
3803 auto &base_type = set<SPIRType>(base_type_id);
3804 base_type.basetype = SPIRType::UInt;
3805 base_type.width = 32;
3806
3807 if (!type.pointer)
3808 return base_type_id;
3809
3810 uint32_t ptr_type_id = next_id++;
3811 auto &ptr_type = set<SPIRType>(ptr_type_id);
3812 ptr_type = base_type;
3813 ptr_type.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01003814 ptr_type.pointer_depth++;
Bill Hollings2964e322018-02-13 14:44:40 -05003815 ptr_type.storage = type.storage;
3816 ptr_type.parent_type = base_type_id;
3817 return ptr_type_id;
3818 }
3819
3820 return type_id;
3821}
3822
Chip Davis5281d992020-06-13 23:03:30 -05003823// Ensure that the type is compatible with the shader input.
Chip Davis06d48342018-11-28 16:26:45 -06003824// If it is, simply return the given type ID.
3825// Otherwise, create a new type, and return its ID.
Bill Hollings548a23d2021-09-20 17:57:11 -04003826uint32_t CompilerMSL::ensure_correct_input_type(uint32_t type_id, uint32_t location, uint32_t component, uint32_t num_components, bool strip_array)
Chip Davis06d48342018-11-28 16:26:45 -06003827{
3828 auto &type = get<SPIRType>(type_id);
3829
Hans-Kristian Arntzen40f628f2021-04-09 10:45:05 +02003830 uint32_t max_array_dimensions = strip_array ? 1 : 0;
3831
3832 // Struct and array types must match exactly.
3833 if (type.basetype == SPIRType::Struct || type.array.size() > max_array_dimensions)
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02003834 return type_id;
3835
Bill Hollings548a23d2021-09-20 17:57:11 -04003836 auto p_va = inputs_by_location.find({location, component});
Chip Davis5281d992020-06-13 23:03:30 -05003837 if (p_va == end(inputs_by_location))
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003838 {
Chip Davis5281d992020-06-13 23:03:30 -05003839 if (num_components > type.vecsize)
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003840 return build_extended_vector_type(type_id, num_components);
3841 else
3842 return type_id;
3843 }
Chip Davis06d48342018-11-28 16:26:45 -06003844
Chip Davis5281d992020-06-13 23:03:30 -05003845 if (num_components == 0)
3846 num_components = p_va->second.vecsize;
3847
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01003848 switch (p_va->second.format)
Chip Davis6db79b82018-12-04 13:54:29 -06003849 {
Chip Davis5281d992020-06-13 23:03:30 -05003850 case MSL_SHADER_INPUT_FORMAT_UINT8:
Chip Davis06d48342018-11-28 16:26:45 -06003851 {
3852 switch (type.basetype)
3853 {
3854 case SPIRType::UByte:
3855 case SPIRType::UShort:
3856 case SPIRType::UInt:
Chip Davis5281d992020-06-13 23:03:30 -05003857 if (num_components > type.vecsize)
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003858 return build_extended_vector_type(type_id, num_components);
3859 else
3860 return type_id;
3861
Chip Davis06d48342018-11-28 16:26:45 -06003862 case SPIRType::Short:
Chip Davis5281d992020-06-13 23:03:30 -05003863 return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
3864 SPIRType::UShort);
Chip Davis06d48342018-11-28 16:26:45 -06003865 case SPIRType::Int:
Chip Davis5281d992020-06-13 23:03:30 -05003866 return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
3867 SPIRType::UInt);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003868
Chip Davis06d48342018-11-28 16:26:45 -06003869 default:
3870 SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader");
3871 }
Chip Davis06d48342018-11-28 16:26:45 -06003872 }
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01003873
Chip Davis688c5fc2020-02-20 21:38:28 -06003874 case MSL_SHADER_INPUT_FORMAT_UINT16:
Chip Davis06d48342018-11-28 16:26:45 -06003875 {
3876 switch (type.basetype)
3877 {
3878 case SPIRType::UShort:
3879 case SPIRType::UInt:
Chip Davis5281d992020-06-13 23:03:30 -05003880 if (num_components > type.vecsize)
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003881 return build_extended_vector_type(type_id, num_components);
3882 else
3883 return type_id;
3884
Chip Davis06d48342018-11-28 16:26:45 -06003885 case SPIRType::Int:
Chip Davis5281d992020-06-13 23:03:30 -05003886 return build_extended_vector_type(type_id, num_components > type.vecsize ? num_components : type.vecsize,
3887 SPIRType::UInt);
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003888
Chip Davis06d48342018-11-28 16:26:45 -06003889 default:
3890 SPIRV_CROSS_THROW("Vertex attribute type mismatch between host and shader");
3891 }
Chip Davis06d48342018-11-28 16:26:45 -06003892 }
3893
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +01003894 default:
Chip Davis5281d992020-06-13 23:03:30 -05003895 if (num_components > type.vecsize)
Hans-Kristian Arntzen93f32652020-01-07 14:05:55 +01003896 type_id = build_extended_vector_type(type_id, num_components);
Chip Davis6db79b82018-12-04 13:54:29 -06003897 break;
3898 }
3899
Chip Davis06d48342018-11-28 16:26:45 -06003900 return type_id;
3901}
3902
Hans-Kristian Arntzen5c1cb7a2019-07-23 15:24:53 +02003903void CompilerMSL::mark_struct_members_packed(const SPIRType &type)
3904{
3905 set_extended_decoration(type.self, SPIRVCrossDecorationPhysicalTypePacked);
3906
3907 // Problem case! Struct needs to be placed at an awkward alignment.
3908 // Mark every member of the child struct as packed.
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02003909 uint32_t mbr_cnt = uint32_t(type.member_types.size());
Hans-Kristian Arntzen5c1cb7a2019-07-23 15:24:53 +02003910 for (uint32_t i = 0; i < mbr_cnt; i++)
3911 {
3912 auto &mbr_type = get<SPIRType>(type.member_types[i]);
3913 if (mbr_type.basetype == SPIRType::Struct)
3914 {
3915 // Recursively mark structs as packed.
3916 auto *struct_type = &mbr_type;
3917 while (!struct_type->array.empty())
3918 struct_type = &get<SPIRType>(struct_type->parent_type);
3919 mark_struct_members_packed(*struct_type);
3920 }
Hans-Kristian Arntzenc62503b2019-07-24 11:52:28 +02003921 else if (!is_scalar(mbr_type))
Hans-Kristian Arntzen5c1cb7a2019-07-23 15:24:53 +02003922 set_extended_member_decoration(type.self, i, SPIRVCrossDecorationPhysicalTypePacked);
3923 }
3924}
3925
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02003926void CompilerMSL::mark_scalar_layout_structs(const SPIRType &type)
3927{
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02003928 uint32_t mbr_cnt = uint32_t(type.member_types.size());
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02003929 for (uint32_t i = 0; i < mbr_cnt; i++)
3930 {
3931 auto &mbr_type = get<SPIRType>(type.member_types[i]);
3932 if (mbr_type.basetype == SPIRType::Struct)
3933 {
Hans-Kristian Arntzenb66a53a2019-07-19 14:43:42 +02003934 auto *struct_type = &mbr_type;
3935 while (!struct_type->array.empty())
3936 struct_type = &get<SPIRType>(struct_type->parent_type);
3937
3938 if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPhysicalTypePacked))
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02003939 continue;
3940
3941 uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, i);
3942 uint32_t msl_size = get_declared_struct_member_size_msl(type, i);
3943 uint32_t spirv_offset = type_struct_member_offset(type, i);
3944 uint32_t spirv_offset_next;
3945 if (i + 1 < mbr_cnt)
3946 spirv_offset_next = type_struct_member_offset(type, i + 1);
3947 else
3948 spirv_offset_next = spirv_offset + msl_size;
3949
3950 // Both are complicated cases. In scalar layout, a struct of float3 might just consume 12 bytes,
3951 // and the next member will be placed at offset 12.
3952 bool struct_is_misaligned = (spirv_offset % msl_alignment) != 0;
3953 bool struct_is_too_large = spirv_offset + msl_size > spirv_offset_next;
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02003954 uint32_t array_stride = 0;
3955 bool struct_needs_explicit_padding = false;
3956
3957 // Verify that if a struct is used as an array that ArrayStride matches the effective size of the struct.
3958 if (!mbr_type.array.empty())
3959 {
3960 array_stride = type_struct_member_array_stride(type, i);
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02003961 uint32_t dimensions = uint32_t(mbr_type.array.size() - 1);
Hans-Kristian Arntzen62241992019-07-23 10:30:37 +02003962 for (uint32_t dim = 0; dim < dimensions; dim++)
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02003963 {
Hans-Kristian Arntzen62241992019-07-23 10:30:37 +02003964 uint32_t array_size = to_array_size_literal(mbr_type, dim);
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02003965 array_stride /= max(array_size, 1u);
3966 }
3967
3968 // Set expected struct size based on ArrayStride.
3969 struct_needs_explicit_padding = true;
3970
3971 // If struct size is larger than array stride, we might be able to fit, if we tightly pack.
3972 if (get_declared_struct_size_msl(*struct_type) > array_stride)
3973 struct_is_too_large = true;
3974 }
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02003975
3976 if (struct_is_misaligned || struct_is_too_large)
Hans-Kristian Arntzen5c1cb7a2019-07-23 15:24:53 +02003977 mark_struct_members_packed(*struct_type);
Hans-Kristian Arntzenb66a53a2019-07-19 14:43:42 +02003978 mark_scalar_layout_structs(*struct_type);
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02003979
3980 if (struct_needs_explicit_padding)
3981 {
3982 msl_size = get_declared_struct_size_msl(*struct_type, true, true);
3983 if (array_stride < msl_size)
3984 {
3985 SPIRV_CROSS_THROW("Cannot express an array stride smaller than size of struct type.");
3986 }
3987 else
3988 {
3989 if (has_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget))
3990 {
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +02003991 if (array_stride !=
3992 get_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget))
3993 SPIRV_CROSS_THROW(
3994 "A struct is used with different array strides. Cannot express this in MSL.");
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02003995 }
3996 else
3997 set_extended_decoration(struct_type->self, SPIRVCrossDecorationPaddingTarget, array_stride);
3998 }
3999 }
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02004000 }
4001 }
4002}
4003
Bill Hollings5550c872017-03-12 17:42:51 -04004004// Sort the members of the struct type by offset, and pack and then pad members where needed
4005// to align MSL members with SPIR-V offsets. The struct members are iterated twice. Packing
4006// occurs first, followed by padding, because packing a member reduces both its size and its
4007// natural alignment, possibly requiring a padding member to be added ahead of it.
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004008void CompilerMSL::align_struct(SPIRType &ib_type, unordered_set<uint32_t> &aligned_structs)
Bill Hollings81757502017-01-29 13:28:20 -05004009{
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004010 // We align structs recursively, so stop any redundant work.
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02004011 ID &ib_type_id = ib_type.self;
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004012 if (aligned_structs.count(ib_type_id))
4013 return;
4014 aligned_structs.insert(ib_type_id);
Bill Hollings81757502017-01-29 13:28:20 -05004015
4016 // Sort the members of the interface structure by their offset.
Bill Hollings484931d2017-02-28 21:44:36 -05004017 // They should already be sorted per SPIR-V spec anyway.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02004018 MemberSorter member_sorter(ib_type, ir.meta[ib_type_id], MemberSorter::Offset);
Bill Hollings81757502017-01-29 13:28:20 -05004019 member_sorter.sort();
4020
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004021 auto mbr_cnt = uint32_t(ib_type.member_types.size());
4022
4023 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
4024 {
4025 // Pack any dependent struct types before we pack a parent struct.
4026 auto &mbr_type = get<SPIRType>(ib_type.member_types[mbr_idx]);
4027 if (mbr_type.basetype == SPIRType::Struct)
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004028 align_struct(mbr_type, aligned_structs);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004029 }
Bill Hollings5550c872017-03-12 17:42:51 -04004030
4031 // Test the alignment of each member, and if a member should be closer to the previous
4032 // member than the default spacing expects, it is likely that the previous member is in
4033 // a packed format. If so, and the previous member is packable, pack it.
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004034 // For example ... this applies to any 3-element vector that is followed by a scalar.
4035 uint32_t msl_offset = 0;
Bill Hollings484931d2017-02-28 21:44:36 -05004036 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
Bill Hollings81757502017-01-29 13:28:20 -05004037 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004038 // This checks the member in isolation, if the member needs some kind of type remapping to conform to SPIR-V
4039 // offsets, array strides and matrix strides.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004040 ensure_member_packing_rules_msl(ib_type, mbr_idx);
Bill Hollingsa3546eb2017-03-06 11:00:23 -05004041
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004042 // Align current offset to the current member's default alignment. If the member was packed, it will observe
4043 // the updated alignment here.
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02004044 uint32_t msl_align_mask = get_declared_struct_member_alignment_msl(ib_type, mbr_idx) - 1;
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +02004045 uint32_t aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask;
Bill Hollings5550c872017-03-12 17:42:51 -04004046
4047 // Fetch the member offset as declared in the SPIRV.
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004048 uint32_t spirv_mbr_offset = get_member_decoration(ib_type_id, mbr_idx, DecorationOffset);
4049 if (spirv_mbr_offset > aligned_msl_offset)
Bill Hollings5550c872017-03-12 17:42:51 -04004050 {
4051 // Since MSL and SPIR-V have slightly different struct member alignment and
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004052 // size rules, we'll pad to standard C-packing rules with a char[] array. If the member is farther
Bill Hollings5550c872017-03-12 17:42:51 -04004053 // away than C-packing, expects, add an inert padding member before the the member.
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004054 uint32_t padding_bytes = spirv_mbr_offset - aligned_msl_offset;
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +02004055 set_extended_member_decoration(ib_type_id, mbr_idx, SPIRVCrossDecorationPaddingTarget, padding_bytes);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004056
4057 // Re-align as a sanity check that aligning post-padding matches up.
4058 msl_offset += padding_bytes;
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +02004059 aligned_msl_offset = (msl_offset + msl_align_mask) & ~msl_align_mask;
Bill Hollings5550c872017-03-12 17:42:51 -04004060 }
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004061 else if (spirv_mbr_offset < aligned_msl_offset)
4062 {
4063 // This should not happen, but deal with unexpected scenarios.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004064 // It *might* happen if a sub-struct has a larger alignment requirement in MSL than SPIR-V.
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004065 SPIRV_CROSS_THROW("Cannot represent buffer block correctly in MSL.");
4066 }
4067
4068 assert(aligned_msl_offset == spirv_mbr_offset);
Bill Hollings5550c872017-03-12 17:42:51 -04004069
4070 // Increment the current offset to be positioned immediately after the current member.
Hans-Kristian Arntzen480acda2018-11-01 14:56:25 +01004071 // Don't do this for the last member since it can be unsized, and it is not relevant for padding purposes here.
4072 if (mbr_idx + 1 < mbr_cnt)
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +02004073 msl_offset = aligned_msl_offset + get_declared_struct_member_size_msl(ib_type, mbr_idx);
Bill Hollings81757502017-01-29 13:28:20 -05004074 }
4075}
4076
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004077bool CompilerMSL::validate_member_packing_rules_msl(const SPIRType &type, uint32_t index) const
Bill Hollings5cb3ce92017-03-02 17:57:26 -08004078{
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004079 auto &mbr_type = get<SPIRType>(type.member_types[index]);
4080 uint32_t spirv_offset = get_member_decoration(type.self, index, DecorationOffset);
Bill Hollings607b0d62018-02-11 16:52:57 -05004081
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004082 if (index + 1 < type.member_types.size())
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +01004083 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004084 // First, we will check offsets. If SPIR-V offset + MSL size > SPIR-V offset of next member,
4085 // we *must* perform some kind of remapping, no way getting around it.
4086 // We can always pad after this member if necessary, so that case is fine.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004087 uint32_t spirv_offset_next = get_member_decoration(type.self, index + 1, DecorationOffset);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004088 assert(spirv_offset_next >= spirv_offset);
4089 uint32_t maximum_size = spirv_offset_next - spirv_offset;
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004090 uint32_t msl_mbr_size = get_declared_struct_member_size_msl(type, index);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004091 if (msl_mbr_size > maximum_size)
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004092 return false;
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +01004093 }
4094
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004095 if (!mbr_type.array.empty())
Hans-Kristian Arntzen217eb5b2019-01-28 11:32:06 +01004096 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004097 // If we have an array type, array stride must match exactly with SPIR-V.
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +02004098
Hans-Kristian Arntzen107ab7c2020-05-06 10:19:09 +02004099 // An exception to this requirement is if we have one array element.
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +02004100 // This comes from DX scalar layout workaround.
4101 // If app tries to be cheeky and access the member out of bounds, this will not work, but this is the best we can do.
Hans-Kristian Arntzen107ab7c2020-05-06 10:19:09 +02004102 // In OpAccessChain with logical memory models, access chains must be in-bounds in SPIR-V specification.
4103 bool relax_array_stride = mbr_type.array.back() == 1 && mbr_type.array_size_literal.back();
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +02004104
4105 if (!relax_array_stride)
4106 {
4107 uint32_t spirv_array_stride = type_struct_member_array_stride(type, index);
4108 uint32_t msl_array_stride = get_declared_struct_member_array_stride_msl(type, index);
4109 if (spirv_array_stride != msl_array_stride)
4110 return false;
4111 }
Hans-Kristian Arntzen217eb5b2019-01-28 11:32:06 +01004112 }
4113
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004114 if (is_matrix(mbr_type))
Bill Hollings607b0d62018-02-11 16:52:57 -05004115 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004116 // Need to check MatrixStride as well.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004117 uint32_t spirv_matrix_stride = type_struct_member_matrix_stride(type, index);
4118 uint32_t msl_matrix_stride = get_declared_struct_member_matrix_stride_msl(type, index);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004119 if (spirv_matrix_stride != msl_matrix_stride)
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004120 return false;
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004121 }
Bill Hollings607b0d62018-02-11 16:52:57 -05004122
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004123 // Now, we check alignment.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004124 uint32_t msl_alignment = get_declared_struct_member_alignment_msl(type, index);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004125 if ((spirv_offset % msl_alignment) != 0)
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004126 return false;
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004127
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004128 // We're in the clear.
4129 return true;
4130}
4131
4132// Here we need to verify that the member type we declare conforms to Offset, ArrayStride or MatrixStride restrictions.
4133// If there is a mismatch, we need to emit remapped types, either normal types, or "packed_X" types.
4134// In odd cases we need to emit packed and remapped types, for e.g. weird matrices or arrays with weird array strides.
4135void CompilerMSL::ensure_member_packing_rules_msl(SPIRType &ib_type, uint32_t index)
4136{
4137 if (validate_member_packing_rules_msl(ib_type, index))
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02004138 return;
4139
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004140 // We failed validation.
4141 // This case will be nightmare-ish to deal with. This could possibly happen if struct alignment does not quite
4142 // match up with what we want. Scalar block layout comes to mind here where we might have to work around the rule
4143 // that struct alignment == max alignment of all members and struct size depends on this alignment.
4144 auto &mbr_type = get<SPIRType>(ib_type.member_types[index]);
4145 if (mbr_type.basetype == SPIRType::Struct)
4146 SPIRV_CROSS_THROW("Cannot perform any repacking for structs when it is used as a member of another struct.");
4147
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +02004148 // Perform remapping here.
Hans-Kristian Arntzen107ab7c2020-05-06 10:19:09 +02004149 // There is nothing to be gained by using packed scalars, so don't attempt it.
4150 if (!is_scalar(ib_type))
4151 set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +02004152
4153 // Try validating again, now with packed.
4154 if (validate_member_packing_rules_msl(ib_type, index))
4155 return;
4156
4157 // We're in deep trouble, and we need to create a new PhysicalType which matches up with what we expect.
4158 // A lot of work goes here ...
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004159 // We will need remapping on Load and Store to translate the types between Logical and Physical.
Hans-Kristian Arntzendd7ebaf2019-07-18 17:05:28 +02004160
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004161 // First, we check if we have small vector std140 array.
4162 // We detect this if we have an array of vectors, and array stride is greater than number of elements.
4163 if (!mbr_type.array.empty() && !is_matrix(mbr_type))
Chip Davis28454fa2019-07-10 18:37:31 -05004164 {
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004165 uint32_t array_stride = type_struct_member_array_stride(ib_type, index);
4166
4167 // Hack off array-of-arrays until we find the array stride per element we must have to make it work.
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +02004168 uint32_t dimensions = uint32_t(mbr_type.array.size() - 1);
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004169 for (uint32_t dim = 0; dim < dimensions; dim++)
4170 array_stride /= max(to_array_size_literal(mbr_type, dim), 1u);
4171
4172 uint32_t elems_per_stride = array_stride / (mbr_type.width / 8);
4173
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02004174 if (elems_per_stride == 3)
4175 SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios.");
4176 else if (elems_per_stride > 4)
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004177 SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL.");
4178
4179 auto physical_type = mbr_type;
4180 physical_type.vecsize = elems_per_stride;
4181 physical_type.parent_type = 0;
4182 uint32_t type_id = ir.increase_bound_by(1);
4183 set<SPIRType>(type_id, physical_type);
4184 set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id);
4185 set_decoration(type_id, DecorationArrayStride, array_stride);
4186
4187 // Remove packed_ for vectors of size 1, 2 and 4.
Bill Hollingsbe812c42021-10-28 19:36:32 -04004188 unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
Chip Davis28454fa2019-07-10 18:37:31 -05004189 }
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004190 else if (is_matrix(mbr_type))
4191 {
4192 // MatrixStride might be std140-esque.
4193 uint32_t matrix_stride = type_struct_member_matrix_stride(ib_type, index);
4194
4195 uint32_t elems_per_stride = matrix_stride / (mbr_type.width / 8);
4196
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02004197 if (elems_per_stride == 3)
4198 SPIRV_CROSS_THROW("Cannot use ArrayStride of 3 elements in remapping scenarios.");
4199 else if (elems_per_stride > 4)
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004200 SPIRV_CROSS_THROW("Cannot represent vectors with more than 4 elements in MSL.");
4201
4202 bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor);
4203
4204 auto physical_type = mbr_type;
4205 physical_type.parent_type = 0;
4206 if (row_major)
4207 physical_type.columns = elems_per_stride;
4208 else
4209 physical_type.vecsize = elems_per_stride;
4210 uint32_t type_id = ir.increase_bound_by(1);
4211 set<SPIRType>(type_id, physical_type);
4212 set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID, type_id);
4213
4214 // Remove packed_ for vectors of size 1, 2 and 4.
Bill Hollingsbe812c42021-10-28 19:36:32 -04004215 unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004216 }
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +02004217 else
4218 SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL.");
4219
4220 // Try validating again, now with physical type remapping.
4221 if (validate_member_packing_rules_msl(ib_type, index))
4222 return;
4223
4224 // We might have a particular odd scalar layout case where the last element of an array
4225 // does not take up as much space as the ArrayStride or MatrixStride. This can happen with DX cbuffers.
4226 // The "proper" workaround for this is extremely painful and essentially impossible in the edge case of float3[],
4227 // so we hack around it by declaring the offending array or matrix with one less array size/col/row,
4228 // and rely on padding to get the correct value. We will technically access arrays out of bounds into the padding region,
4229 // but it should spill over gracefully without too much trouble. We rely on behavior like this for unsized arrays anyways.
4230
4231 // E.g. we might observe a physical layout of:
4232 // { float2 a[2]; float b; } in cbuffer layout where ArrayStride of a is 16, but offset of b is 24, packed right after a[1] ...
4233 uint32_t type_id = get_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID);
4234 auto &type = get<SPIRType>(type_id);
4235
4236 // Modify the physical type in-place. This is safe since each physical type workaround is a copy.
4237 if (is_array(type))
4238 {
4239 if (type.array.back() > 1)
4240 {
4241 if (!type.array_size_literal.back())
4242 SPIRV_CROSS_THROW("Cannot apply scalar layout workaround with spec constant array size.");
4243 type.array.back() -= 1;
4244 }
4245 else
4246 {
4247 // We have an array of size 1, so we cannot decrement that. Our only option now is to
4248 // force a packed layout instead, and drop the physical type remap since ArrayStride is meaningless now.
4249 unset_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypeID);
4250 set_extended_member_decoration(ib_type.self, index, SPIRVCrossDecorationPhysicalTypePacked);
4251 }
4252 }
4253 else if (is_matrix(type))
4254 {
4255 bool row_major = has_member_decoration(ib_type.self, index, DecorationRowMajor);
4256 if (!row_major)
4257 {
4258 // Slice off one column. If we only have 2 columns, this might turn the matrix into a vector with one array element instead.
4259 if (type.columns > 2)
4260 {
4261 type.columns--;
4262 }
4263 else if (type.columns == 2)
4264 {
4265 type.columns = 1;
4266 assert(type.array.empty());
4267 type.array.push_back(1);
4268 type.array_size_literal.push_back(true);
4269 }
4270 }
4271 else
4272 {
4273 // Slice off one row. If we only have 2 rows, this might turn the matrix into a vector with one array element instead.
4274 if (type.vecsize > 2)
4275 {
4276 type.vecsize--;
4277 }
4278 else if (type.vecsize == 2)
4279 {
4280 type.vecsize = type.columns;
4281 type.columns = 1;
4282 assert(type.array.empty());
4283 type.array.push_back(1);
4284 type.array_size_literal.push_back(true);
4285 }
4286 }
4287 }
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004288
4289 // This better validate now, or we must fail gracefully.
4290 if (!validate_member_packing_rules_msl(ib_type, index))
4291 SPIRV_CROSS_THROW("Found a buffer packing case which we cannot represent in MSL.");
Chip Davis28454fa2019-07-10 18:37:31 -05004292}
4293
Hans-Kristian Arntzen73d9da72019-01-17 12:21:16 +01004294void CompilerMSL::emit_store_statement(uint32_t lhs_expression, uint32_t rhs_expression)
Hans-Kristian Arntzen15b52be2019-01-17 10:06:23 +01004295{
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004296 auto &type = expression_type(rhs_expression);
4297
4298 bool lhs_remapped_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID);
4299 bool lhs_packed_type = has_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypePacked);
4300 auto *lhs_e = maybe_get<SPIRExpression>(lhs_expression);
4301 auto *rhs_e = maybe_get<SPIRExpression>(rhs_expression);
4302
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004303 bool transpose = lhs_e && lhs_e->need_transpose;
4304
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004305 // No physical type remapping, and no packed type, so can just emit a store directly.
4306 if (!lhs_remapped_type && !lhs_packed_type)
Hans-Kristian Arntzende7e5cc2019-01-17 11:22:24 +01004307 {
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004308 // We might not be dealing with remapped physical types or packed types,
4309 // but we might be doing a clean store to a row-major matrix.
4310 // In this case, we just flip transpose states, and emit the store, a transpose must be in the RHS expression, if any.
4311 if (is_matrix(type) && lhs_e && lhs_e->need_transpose)
4312 {
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004313 lhs_e->need_transpose = false;
Hans-Kristian Arntzen6057ffc2019-07-22 15:49:17 +02004314
4315 if (rhs_e && rhs_e->need_transpose)
4316 {
4317 // Direct copy, but might need to unpack RHS.
4318 // Skip the transpose, as we will transpose when writing to LHS and transpose(transpose(T)) == T.
4319 rhs_e->need_transpose = false;
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +02004320 statement(to_expression(lhs_expression), " = ", to_unpacked_row_major_matrix_expression(rhs_expression),
4321 ";");
Hans-Kristian Arntzen6057ffc2019-07-22 15:49:17 +02004322 rhs_e->need_transpose = true;
4323 }
4324 else
Hans-Kristian Arntzen609d0872019-07-22 16:06:09 +02004325 statement(to_expression(lhs_expression), " = transpose(", to_unpacked_expression(rhs_expression), ");");
Hans-Kristian Arntzen6057ffc2019-07-22 15:49:17 +02004326
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004327 lhs_e->need_transpose = true;
Hans-Kristian Arntzen6057ffc2019-07-22 15:49:17 +02004328 register_write(lhs_expression);
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004329 }
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004330 else if (lhs_e && lhs_e->need_transpose)
4331 {
4332 lhs_e->need_transpose = false;
4333
4334 // Storing a column to a row-major matrix. Unroll the write.
4335 for (uint32_t c = 0; c < type.vecsize; c++)
4336 {
4337 auto lhs_expr = to_dereferenced_expression(lhs_expression);
4338 auto column_index = lhs_expr.find_last_of('[');
4339 if (column_index != string::npos)
4340 {
4341 statement(lhs_expr.insert(column_index, join('[', c, ']')), " = ",
4342 to_extract_component_expression(rhs_expression, c), ";");
4343 }
4344 }
4345 lhs_e->need_transpose = true;
Hans-Kristian Arntzenf2d6a772019-07-22 13:06:30 +02004346 register_write(lhs_expression);
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004347 }
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004348 else
4349 CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression);
4350 }
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004351 else if (!lhs_remapped_type && !is_matrix(type) && !transpose)
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004352 {
4353 // Even if the target type is packed, we can directly store to it. We cannot store to packed matrices directly,
4354 // since they are declared as array of vectors instead, and we need the fallback path below.
Hans-Kristian Arntzen73d9da72019-01-17 12:21:16 +01004355 CompilerGLSL::emit_store_statement(lhs_expression, rhs_expression);
Hans-Kristian Arntzende7e5cc2019-01-17 11:22:24 +01004356 }
Hans-Kristian Arntzen15b52be2019-01-17 10:06:23 +01004357 else
4358 {
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004359 // Special handling when storing to a remapped physical type.
4360 // This is mostly to deal with std140 padded matrices or vectors.
Hans-Kristian Arntzen15b52be2019-01-17 10:06:23 +01004361
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02004362 TypeID physical_type_id = lhs_remapped_type ?
4363 ID(get_extended_decoration(lhs_expression, SPIRVCrossDecorationPhysicalTypeID)) :
4364 type.self;
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004365
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004366 auto &physical_type = get<SPIRType>(physical_type_id);
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004367
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004368 if (is_matrix(type))
Chip Davis28454fa2019-07-10 18:37:31 -05004369 {
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004370 const char *packed_pfx = lhs_packed_type ? "packed_" : "";
4371
Chip Davis28454fa2019-07-10 18:37:31 -05004372 // Packed matrices are stored as arrays of packed vectors, so we need
4373 // to assign the vectors one at a time.
4374 // For row-major matrices, we need to transpose the *right-hand* side,
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004375 // not the left-hand side.
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004376
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004377 // Lots of cases to cover here ...
4378
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004379 bool rhs_transpose = rhs_e && rhs_e->need_transpose;
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004380 SPIRType write_type = type;
4381 string cast_expr;
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004382
4383 // We're dealing with transpose manually.
4384 if (rhs_transpose)
4385 rhs_e->need_transpose = false;
4386
Chip Davis28454fa2019-07-10 18:37:31 -05004387 if (transpose)
4388 {
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004389 // We're dealing with transpose manually.
Chip Davis28454fa2019-07-10 18:37:31 -05004390 lhs_e->need_transpose = false;
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004391 write_type.vecsize = type.columns;
4392 write_type.columns = 1;
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004393
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004394 if (physical_type.columns != type.columns)
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004395 cast_expr = join("(device ", packed_pfx, type_to_glsl(write_type), "&)");
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004396
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004397 if (rhs_transpose)
4398 {
4399 // If RHS is also transposed, we can just copy row by row.
4400 for (uint32_t i = 0; i < type.vecsize; i++)
4401 {
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004402 statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ",
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +02004403 to_unpacked_row_major_matrix_expression(rhs_expression), "[", i, "];");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004404 }
4405 }
4406 else
4407 {
4408 auto vector_type = expression_type(rhs_expression);
4409 vector_type.vecsize = vector_type.columns;
4410 vector_type.columns = 1;
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004411
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004412 // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad,
4413 // so pick out individual components instead.
4414 for (uint32_t i = 0; i < type.vecsize; i++)
4415 {
4416 string rhs_row = type_to_glsl_constructor(vector_type) + "(";
4417 for (uint32_t j = 0; j < vector_type.vecsize; j++)
4418 {
Hans-Kristian Arntzen19f5cd32019-07-22 13:25:45 +02004419 rhs_row += join(to_enclosed_unpacked_expression(rhs_expression), "[", j, "][", i, "]");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004420 if (j + 1 < vector_type.vecsize)
4421 rhs_row += ", ";
4422 }
4423 rhs_row += ")";
4424
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004425 statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004426 }
4427 }
4428
4429 // We're dealing with transpose manually.
Chip Davis28454fa2019-07-10 18:37:31 -05004430 lhs_e->need_transpose = true;
Chip Davis28454fa2019-07-10 18:37:31 -05004431 }
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004432 else
4433 {
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004434 write_type.columns = 1;
4435
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004436 if (physical_type.vecsize != type.vecsize)
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004437 cast_expr = join("(device ", packed_pfx, type_to_glsl(write_type), "&)");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004438
4439 if (rhs_transpose)
4440 {
4441 auto vector_type = expression_type(rhs_expression);
4442 vector_type.columns = 1;
4443
4444 // Transpose on the fly. Emitting a lot of full transpose() ops and extracting lanes seems very bad,
4445 // so pick out individual components instead.
4446 for (uint32_t i = 0; i < type.columns; i++)
4447 {
4448 string rhs_row = type_to_glsl_constructor(vector_type) + "(";
4449 for (uint32_t j = 0; j < vector_type.vecsize; j++)
4450 {
Hans-Kristian Arntzen14afb962019-07-22 12:03:12 +02004451 // Need to explicitly unpack expression since we've mucked with transpose state.
Hans-Kristian Arntzen7277c7a2019-07-23 11:36:54 +02004452 auto unpacked_expr = to_unpacked_row_major_matrix_expression(rhs_expression);
Hans-Kristian Arntzen14afb962019-07-22 12:03:12 +02004453 rhs_row += join(unpacked_expr, "[", j, "][", i, "]");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004454 if (j + 1 < vector_type.vecsize)
4455 rhs_row += ", ";
4456 }
4457 rhs_row += ")";
4458
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004459 statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ", rhs_row, ";");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004460 }
4461 }
4462 else
4463 {
4464 // Copy column-by-column.
4465 for (uint32_t i = 0; i < type.columns; i++)
4466 {
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004467 statement(cast_expr, to_enclosed_expression(lhs_expression), "[", i, "]", " = ",
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +02004468 to_enclosed_unpacked_expression(rhs_expression), "[", i, "];");
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004469 }
4470 }
4471 }
4472
4473 // We're dealing with transpose manually.
4474 if (rhs_transpose)
4475 rhs_e->need_transpose = true;
Chip Davis28454fa2019-07-10 18:37:31 -05004476 }
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004477 else if (transpose)
4478 {
4479 lhs_e->need_transpose = false;
4480
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004481 SPIRType write_type = type;
4482 write_type.vecsize = 1;
4483 write_type.columns = 1;
4484
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004485 // Storing a column to a row-major matrix. Unroll the write.
4486 for (uint32_t c = 0; c < type.vecsize; c++)
4487 {
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004488 auto lhs_expr = to_enclosed_expression(lhs_expression);
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004489 auto column_index = lhs_expr.find_last_of('[');
4490 if (column_index != string::npos)
4491 {
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004492 statement("((device ", type_to_glsl(write_type), "*)&",
4493 lhs_expr.insert(column_index, join('[', c, ']', ")")), " = ",
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +02004494 to_extract_component_expression(rhs_expression, c), ";");
4495 }
4496 }
4497
4498 lhs_e->need_transpose = true;
4499 }
Hans-Kristian Arntzen745a2f72019-07-22 13:05:23 +02004500 else if ((is_matrix(physical_type) || is_array(physical_type)) && physical_type.vecsize > type.vecsize)
Chip Davise5fa7ed2019-07-09 20:28:02 -05004501 {
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004502 assert(type.vecsize >= 1 && type.vecsize <= 3);
4503
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +02004504 // If we have packed types, we cannot use swizzled stores.
4505 // We could technically unroll the store for each element if needed.
4506 // When remapping to a std140 physical type, we always get float4,
4507 // and the packed decoration should always be removed.
4508 assert(!lhs_packed_type);
4509
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004510 string lhs = to_dereferenced_expression(lhs_expression);
4511 string rhs = to_pointer_expression(rhs_expression);
4512
Chip Davise5fa7ed2019-07-09 20:28:02 -05004513 // Unpack the expression so we can store to it with a float or float2.
4514 // It's still an l-value, so it's fine. Most other unpacking of expressions turn them into r-values instead.
Hans-Kristian Arntzen711300b2020-07-01 14:13:10 +02004515 lhs = join("(device ", type_to_glsl(type), "&)", enclose_expression(lhs));
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004516 if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs))
4517 statement(lhs, " = ", rhs, ";");
Chip Davise5fa7ed2019-07-09 20:28:02 -05004518 }
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004519 else if (!is_matrix(type))
Chip Davis28454fa2019-07-10 18:37:31 -05004520 {
Hans-Kristian Arntzen180a6b32019-07-22 12:56:14 +02004521 string lhs = to_dereferenced_expression(lhs_expression);
4522 string rhs = to_pointer_expression(rhs_expression);
Chip Davis28454fa2019-07-10 18:37:31 -05004523 if (!optimize_read_modify_write(expression_type(rhs_expression), lhs, rhs))
4524 statement(lhs, " = ", rhs, ";");
4525 }
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004526
Hans-Kristian Arntzen15b52be2019-01-17 10:06:23 +01004527 register_write(lhs_expression);
4528 }
4529}
4530
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004531static bool expression_ends_with(const string &expr_str, const std::string &ending)
Mark Satterthwaite9ce31582019-08-14 10:57:23 -04004532{
4533 if (expr_str.length() >= ending.length())
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004534 return (expr_str.compare(expr_str.length() - ending.length(), ending.length(), ending) == 0);
Mark Satterthwaite9ce31582019-08-14 10:57:23 -04004535 else
4536 return false;
4537}
4538
Bill Hollingsb332bae2017-03-01 13:07:40 -05004539// Converts the format of the current expression from packed to unpacked,
4540// by wrapping the expression in a constructor of the appropriate type.
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004541// Also, handle special physical ID remapping scenarios, similar to emit_store_statement().
Hans-Kristian Arntzen12c50202019-07-19 13:03:08 +02004542string CompilerMSL::unpack_expression_type(string expr_str, const SPIRType &type, uint32_t physical_type_id,
4543 bool packed, bool row_major)
Bill Hollingsb332bae2017-03-01 13:07:40 -05004544{
Hans-Kristian Arntzen6057ffc2019-07-22 15:49:17 +02004545 // Trivial case, nothing to do.
4546 if (physical_type_id == 0 && !packed)
4547 return expr_str;
4548
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004549 const SPIRType *physical_type = nullptr;
4550 if (physical_type_id)
4551 physical_type = &get<SPIRType>(physical_type_id);
Hans-Kristian Arntzen432aaed2019-01-17 11:39:16 +01004552
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004553 static const char *swizzle_lut[] = {
4554 ".x",
4555 ".xy",
4556 ".xyz",
4557 };
4558
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004559 if (physical_type && is_vector(*physical_type) && is_array(*physical_type) &&
4560 physical_type->vecsize > type.vecsize && !expression_ends_with(expr_str, swizzle_lut[type.vecsize - 1]))
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004561 {
Hans-Kristian Arntzend9afa9e2019-11-07 11:29:40 +01004562 // std140 array cases for vectors.
4563 assert(type.vecsize >= 1 && type.vecsize <= 3);
4564 return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1];
4565 }
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +01004566 else if (physical_type && is_matrix(*physical_type) && is_vector(type) && physical_type->vecsize > type.vecsize)
Hans-Kristian Arntzend9afa9e2019-11-07 11:29:40 +01004567 {
4568 // Extract column from padded matrix.
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004569 assert(type.vecsize >= 1 && type.vecsize <= 3);
4570 return enclose_expression(expr_str) + swizzle_lut[type.vecsize - 1];
4571 }
Chip Davis28454fa2019-07-10 18:37:31 -05004572 else if (is_matrix(type))
4573 {
4574 // Packed matrices are stored as arrays of packed vectors. Unfortunately,
4575 // we can't just pass the array straight to the matrix constructor. We have to
4576 // pass each vector individually, so that they can be unpacked to normal vectors.
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004577 if (!physical_type)
4578 physical_type = &type;
Hans-Kristian Arntzen12c50202019-07-19 13:03:08 +02004579
4580 uint32_t vecsize = type.vecsize;
4581 uint32_t columns = type.columns;
4582 if (row_major)
4583 swap(vecsize, columns);
4584
4585 uint32_t physical_vecsize = row_major ? physical_type->columns : physical_type->vecsize;
4586
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004587 const char *base_type = type.width == 16 ? "half" : "float";
Hans-Kristian Arntzen19f5cd32019-07-22 13:25:45 +02004588 string unpack_expr = join(base_type, columns, "x", vecsize, "(");
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004589
4590 const char *load_swiz = "";
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004591
Hans-Kristian Arntzen12c50202019-07-19 13:03:08 +02004592 if (physical_vecsize != vecsize)
4593 load_swiz = swizzle_lut[vecsize - 1];
4594
4595 for (uint32_t i = 0; i < columns; i++)
Chip Davis28454fa2019-07-10 18:37:31 -05004596 {
4597 if (i > 0)
4598 unpack_expr += ", ";
Hans-Kristian Arntzen12c50202019-07-19 13:03:08 +02004599
4600 if (packed)
4601 unpack_expr += join(base_type, physical_vecsize, "(", expr_str, "[", i, "]", ")", load_swiz);
4602 else
4603 unpack_expr += join(expr_str, "[", i, "]", load_swiz);
Chip Davis28454fa2019-07-10 18:37:31 -05004604 }
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +02004605
Chip Davis28454fa2019-07-10 18:37:31 -05004606 unpack_expr += ")";
4607 return unpack_expr;
4608 }
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +01004609 else
Lukas Hermanns0853bca2019-10-09 17:59:47 -04004610 {
Hans-Kristian Arntzen0bbe0412019-11-07 11:33:00 +01004611 return join(type_to_glsl(type), "(", expr_str, ")");
Lukas Hermanns0853bca2019-10-09 17:59:47 -04004612 }
Bill Hollingsb332bae2017-03-01 13:07:40 -05004613}
4614
Bill Hollings103aabf2016-04-06 17:42:27 -04004615// Emits the file header info
4616void CompilerMSL::emit_header()
4617{
Hans-Kristian Arntzen23db7442019-04-09 12:28:46 +02004618 // This particular line can be overridden during compilation, so make it a flag and not a pragma line.
4619 if (suppress_missing_prototypes)
4620 statement("#pragma clang diagnostic ignored \"-Wmissing-prototypes\"");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004621
4622 // Disable warning about missing braces for array<T> template to make arrays a value type
4623 if (spv_function_implementations.count(SPVFuncImplUnsafeArray) != 0)
4624 statement("#pragma clang diagnostic ignored \"-Wmissing-braces\"");
4625
Bill Hollings6371d9e2018-01-06 00:51:25 -05004626 for (auto &pragma : pragma_lines)
4627 statement(pragma);
Bill Hollings4c198bb2017-01-20 11:24:44 -05004628
Hans-Kristian Arntzen23db7442019-04-09 12:28:46 +02004629 if (!pragma_lines.empty() || suppress_missing_prototypes)
Bill Hollings2d0d3282017-01-20 11:33:59 -05004630 statement("");
Rob Fischere2a37b62016-09-17 12:21:37 +09004631
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02004632 statement("#include <metal_stdlib>");
4633 statement("#include <simd/simd.h>");
Bill Hollings8f6df772017-05-19 18:14:08 -04004634
4635 for (auto &header : header_lines)
4636 statement(header);
4637
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02004638 statement("");
4639 statement("using namespace metal;");
4640 statement("");
Bill Hollings607b0d62018-02-11 16:52:57 -05004641
4642 for (auto &td : typedef_lines)
4643 statement(td);
4644
4645 if (!typedef_lines.empty())
4646 statement("");
Bill Hollings103aabf2016-04-06 17:42:27 -04004647}
4648
Bill Hollings8f6df772017-05-19 18:14:08 -04004649void CompilerMSL::add_pragma_line(const string &line)
4650{
Bill Hollings607b0d62018-02-11 16:52:57 -05004651 auto rslt = pragma_lines.insert(line);
4652 if (rslt.second)
Hans-Kristian Arntzen317144a2019-04-05 12:06:10 +02004653 force_recompile();
Bill Hollings607b0d62018-02-11 16:52:57 -05004654}
4655
4656void CompilerMSL::add_typedef_line(const string &line)
4657{
4658 auto rslt = typedef_lines.insert(line);
4659 if (rslt.second)
Hans-Kristian Arntzen317144a2019-04-05 12:06:10 +02004660 force_recompile();
Bill Hollings8f6df772017-05-19 18:14:08 -04004661}
4662
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004663// Template struct like spvUnsafeArray<> need to be declared *before* any resources are declared
Lukas Hermanns51be6012019-09-17 15:10:39 -04004664void CompilerMSL::emit_custom_templates()
4665{
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004666 for (const auto &spv_func : spv_function_implementations)
Lukas Hermanns51be6012019-09-17 15:10:39 -04004667 {
4668 switch (spv_func)
4669 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004670 case SPVFuncImplUnsafeArray:
4671 statement("template<typename T, size_t Num>");
4672 statement("struct spvUnsafeArray");
4673 begin_scope();
4674 statement("T elements[Num ? Num : 1];");
4675 statement("");
4676 statement("thread T& operator [] (size_t pos) thread");
4677 begin_scope();
4678 statement("return elements[pos];");
4679 end_scope();
4680 statement("constexpr const thread T& operator [] (size_t pos) const thread");
4681 begin_scope();
4682 statement("return elements[pos];");
4683 end_scope();
4684 statement("");
4685 statement("device T& operator [] (size_t pos) device");
4686 begin_scope();
4687 statement("return elements[pos];");
4688 end_scope();
4689 statement("constexpr const device T& operator [] (size_t pos) const device");
4690 begin_scope();
4691 statement("return elements[pos];");
4692 end_scope();
4693 statement("");
4694 statement("constexpr const constant T& operator [] (size_t pos) const constant");
4695 begin_scope();
4696 statement("return elements[pos];");
4697 end_scope();
4698 statement("");
4699 statement("threadgroup T& operator [] (size_t pos) threadgroup");
4700 begin_scope();
4701 statement("return elements[pos];");
4702 end_scope();
4703 statement("constexpr const threadgroup T& operator [] (size_t pos) const threadgroup");
4704 begin_scope();
4705 statement("return elements[pos];");
4706 end_scope();
4707 end_scope_decl();
4708 statement("");
4709 break;
4710
4711 default:
4712 break;
Lukas Hermanns51be6012019-09-17 15:10:39 -04004713 }
4714 }
4715}
Lukas Hermanns51be6012019-09-17 15:10:39 -04004716
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004717// Emits any needed custom function bodies.
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004718// Metal helper functions must be static force-inline, i.e. static inline __attribute__((always_inline))
4719// otherwise they will cause problems when linked together in a single Metallib.
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004720void CompilerMSL::emit_custom_functions()
4721{
Corentin Wallezbcd71532020-09-04 10:04:25 +02004722 for (uint32_t i = kArrayCopyMultidimMax; i >= 2; i--)
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004723 if (spv_function_implementations.count(static_cast<SPVFuncImpl>(SPVFuncImplArrayCopyMultidimBase + i)))
4724 spv_function_implementations.insert(static_cast<SPVFuncImpl>(SPVFuncImplArrayCopyMultidimBase + i - 1));
4725
Chip Davis39dce882019-08-02 15:11:19 -05004726 if (spv_function_implementations.count(SPVFuncImplDynamicImageSampler))
4727 {
4728 // Unfortunately, this one needs a lot of the other functions to compile OK.
4729 if (!msl_options.supports_msl_version(2))
4730 SPIRV_CROSS_THROW(
4731 "spvDynamicImageSampler requires default-constructible texture objects, which require MSL 2.0.");
4732 spv_function_implementations.insert(SPVFuncImplForwardArgs);
4733 spv_function_implementations.insert(SPVFuncImplTextureSwizzle);
4734 if (msl_options.swizzle_texture_samples)
4735 spv_function_implementations.insert(SPVFuncImplGatherSwizzle);
4736 for (uint32_t i = SPVFuncImplChromaReconstructNearest2Plane;
4737 i <= SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane; i++)
4738 spv_function_implementations.insert(static_cast<SPVFuncImpl>(i));
4739 spv_function_implementations.insert(SPVFuncImplExpandITUFullRange);
4740 spv_function_implementations.insert(SPVFuncImplExpandITUNarrowRange);
4741 spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT709);
4742 spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT601);
4743 spv_function_implementations.insert(SPVFuncImplConvertYCbCrBT2020);
4744 }
4745
4746 for (uint32_t i = SPVFuncImplChromaReconstructNearest2Plane;
4747 i <= SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane; i++)
4748 if (spv_function_implementations.count(static_cast<SPVFuncImpl>(i)))
4749 spv_function_implementations.insert(SPVFuncImplForwardArgs);
4750
4751 if (spv_function_implementations.count(SPVFuncImplTextureSwizzle) ||
4752 spv_function_implementations.count(SPVFuncImplGatherSwizzle) ||
4753 spv_function_implementations.count(SPVFuncImplGatherCompareSwizzle))
4754 {
4755 spv_function_implementations.insert(SPVFuncImplForwardArgs);
4756 spv_function_implementations.insert(SPVFuncImplGetSwizzle);
4757 }
4758
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004759 for (const auto &spv_func : spv_function_implementations)
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004760 {
Bill Hollings8f6df772017-05-19 18:14:08 -04004761 switch (spv_func)
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004762 {
Bill Hollings8f6df772017-05-19 18:14:08 -04004763 case SPVFuncImplMod:
4764 statement("// Implementation of the GLSL mod() function, which is slightly different than Metal fmod()");
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004765 statement("template<typename Tx, typename Ty>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004766 statement("inline Tx mod(Tx x, Ty y)");
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05004767 begin_scope();
4768 statement("return x - y * floor(x / y);");
4769 end_scope();
4770 statement("");
4771 break;
4772
Bill Hollings8f6df772017-05-19 18:14:08 -04004773 case SPVFuncImplRadians:
4774 statement("// Implementation of the GLSL radians() function");
4775 statement("template<typename T>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004776 statement("inline T radians(T d)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004777 begin_scope();
Hans-Kristian Arntzen18ad1be2018-03-07 10:24:21 +01004778 statement("return d * T(0.01745329251);");
Bill Hollings8f6df772017-05-19 18:14:08 -04004779 end_scope();
4780 statement("");
4781 break;
4782
4783 case SPVFuncImplDegrees:
4784 statement("// Implementation of the GLSL degrees() function");
4785 statement("template<typename T>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004786 statement("inline T degrees(T r)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004787 begin_scope();
Hans-Kristian Arntzen18ad1be2018-03-07 10:24:21 +01004788 statement("return r * T(57.2957795131);");
Bill Hollings8f6df772017-05-19 18:14:08 -04004789 end_scope();
4790 statement("");
4791 break;
4792
4793 case SPVFuncImplFindILsb:
4794 statement("// Implementation of the GLSL findLSB() function");
4795 statement("template<typename T>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004796 statement("inline T spvFindLSB(T x)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004797 begin_scope();
Bill Hollings1c180782017-11-05 21:34:42 -05004798 statement("return select(ctz(x), T(-1), x == T(0));");
Bill Hollings8f6df772017-05-19 18:14:08 -04004799 end_scope();
4800 statement("");
4801 break;
4802
4803 case SPVFuncImplFindUMsb:
4804 statement("// Implementation of the unsigned GLSL findMSB() function");
4805 statement("template<typename T>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004806 statement("inline T spvFindUMSB(T x)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004807 begin_scope();
Bill Hollings1c180782017-11-05 21:34:42 -05004808 statement("return select(clz(T(0)) - (clz(x) + T(1)), T(-1), x == T(0));");
Bill Hollings8f6df772017-05-19 18:14:08 -04004809 end_scope();
4810 statement("");
4811 break;
4812
4813 case SPVFuncImplFindSMsb:
4814 statement("// Implementation of the signed GLSL findMSB() function");
4815 statement("template<typename T>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004816 statement("inline T spvFindSMSB(T x)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004817 begin_scope();
Bill Hollings1c180782017-11-05 21:34:42 -05004818 statement("T v = select(x, T(-1) - x, x < T(0));");
4819 statement("return select(clz(T(0)) - (clz(v) + T(1)), T(-1), v == T(0));");
4820 end_scope();
4821 statement("");
4822 break;
4823
Connor McLaughlin1dd676c2018-11-07 22:24:21 +10004824 case SPVFuncImplSSign:
4825 statement("// Implementation of the GLSL sign() function for integer types");
4826 statement("template<typename T, typename E = typename enable_if<is_integral<T>::value>::type>");
Thomas Roughton6338f0a2019-06-10 11:55:39 +12004827 statement("inline T sign(T x)");
Connor McLaughlin1dd676c2018-11-07 22:24:21 +10004828 begin_scope();
4829 statement("return select(select(select(x, T(0), x == T(0)), T(1), x > T(0)), T(-1), x < T(0));");
4830 end_scope();
4831 statement("");
4832 break;
4833
Bill Hollings1c180782017-11-05 21:34:42 -05004834 case SPVFuncImplArrayCopy:
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004835 case SPVFuncImplArrayOfArrayCopy2Dim:
4836 case SPVFuncImplArrayOfArrayCopy3Dim:
4837 case SPVFuncImplArrayOfArrayCopy4Dim:
4838 case SPVFuncImplArrayOfArrayCopy5Dim:
4839 case SPVFuncImplArrayOfArrayCopy6Dim:
4840 {
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02004841 // Unfortunately we cannot template on the address space, so combinatorial explosion it is.
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004842 static const char *function_name_tags[] = {
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02004843 "FromConstantToStack", "FromConstantToThreadGroup", "FromStackToStack",
4844 "FromStackToThreadGroup", "FromThreadGroupToStack", "FromThreadGroupToThreadGroup",
4845 "FromDeviceToDevice", "FromConstantToDevice", "FromStackToDevice",
4846 "FromThreadGroupToDevice", "FromDeviceToStack", "FromDeviceToThreadGroup",
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004847 };
4848
4849 static const char *src_address_space[] = {
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02004850 "constant", "constant", "thread const", "thread const",
4851 "threadgroup const", "threadgroup const", "device const", "constant",
4852 "thread const", "threadgroup const", "device const", "device const",
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004853 };
4854
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02004855 static const char *dst_address_space[] = {
Hans-Kristian Arntzen3ccfbce2019-08-28 14:25:26 +02004856 "thread", "threadgroup", "thread", "threadgroup", "thread", "threadgroup",
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02004857 "device", "device", "device", "device", "thread", "threadgroup",
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02004858 };
4859
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02004860 for (uint32_t variant = 0; variant < 12; variant++)
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004861 {
4862 uint32_t dimensions = spv_func - SPVFuncImplArrayCopyMultidimBase;
4863 string tmp = "template<typename T";
Bill Hollingsdaa831f2018-09-20 16:10:42 -04004864 for (uint8_t i = 0; i < dimensions; i++)
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004865 {
4866 tmp += ", uint ";
4867 tmp += 'A' + i;
4868 }
4869 tmp += ">";
4870 statement(tmp);
4871
4872 string array_arg;
Bill Hollingsdaa831f2018-09-20 16:10:42 -04004873 for (uint8_t i = 0; i < dimensions; i++)
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004874 {
4875 array_arg += "[";
4876 array_arg += 'A' + i;
4877 array_arg += "]";
4878 }
4879
Thomas Roughton6b540322019-08-30 20:25:40 +12004880 statement("inline void spvArrayCopy", function_name_tags[variant], dimensions, "(",
4881 dst_address_space[variant], " T (&dst)", array_arg, ", ", src_address_space[variant],
4882 " T (&src)", array_arg, ")");
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004883
4884 begin_scope();
4885 statement("for (uint i = 0; i < A; i++)");
4886 begin_scope();
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02004887
4888 if (dimensions == 1)
4889 statement("dst[i] = src[i];");
4890 else
4891 statement("spvArrayCopy", function_name_tags[variant], dimensions - 1, "(dst[i], src[i]);");
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02004892 end_scope();
4893 end_scope();
4894 statement("");
4895 }
4896 break;
4897 }
4898
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004899 // Support for Metal 2.1's new texture_buffer type.
Bill Hollings4c5142b2018-06-26 17:30:21 -04004900 case SPVFuncImplTexelBufferCoords:
4901 {
Mark Satterthwaite239e0472019-08-14 10:43:04 -04004902 if (msl_options.texel_buffer_texture_width > 0)
4903 {
Lukas Hermannsa9f3c982019-09-13 14:03:02 -04004904 string tex_width_str = convert_to_string(msl_options.texel_buffer_texture_width);
4905 statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004906 statement(force_inline);
Lukas Hermannsa9f3c982019-09-13 14:03:02 -04004907 statement("uint2 spvTexelBufferCoord(uint tc)");
4908 begin_scope();
4909 statement(join("return uint2(tc % ", tex_width_str, ", tc / ", tex_width_str, ");"));
4910 end_scope();
4911 statement("");
Mark Satterthwaite239e0472019-08-14 10:43:04 -04004912 }
4913 else
4914 {
4915 statement("// Returns 2D texture coords corresponding to 1D texel buffer coords");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004916 statement(
4917 "#define spvTexelBufferCoord(tc, tex) uint2((tc) % (tex).get_width(), (tc) / (tex).get_width())");
Lukas Hermanns51be6012019-09-17 15:10:39 -04004918 statement("");
Mark Satterthwaite239e0472019-08-14 10:43:04 -04004919 }
Bill Hollings4c5142b2018-06-26 17:30:21 -04004920 break;
4921 }
4922
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004923 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04004924 case SPVFuncImplImage2DAtomicCoords:
4925 {
Chip Davis21d38f72020-10-13 13:20:49 -05004926 if (msl_options.supports_msl_version(1, 2))
4927 {
4928 statement("// The required alignment of a linear texture of R32Uint format.");
4929 statement("constant uint spvLinearTextureAlignmentOverride [[function_constant(",
4930 msl_options.r32ui_alignment_constant_id, ")]];");
4931 statement("constant uint spvLinearTextureAlignment = ",
4932 "is_function_constant_defined(spvLinearTextureAlignmentOverride) ? ",
4933 "spvLinearTextureAlignmentOverride : ", msl_options.r32ui_linear_texture_alignment, ";");
4934 }
4935 else
4936 {
4937 statement("// The required alignment of a linear texture of R32Uint format.");
4938 statement("constant uint spvLinearTextureAlignment = ", msl_options.r32ui_linear_texture_alignment,
4939 ";");
4940 }
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04004941 statement("// Returns buffer coords corresponding to 2D texture coords for emulating 2D texture atomics");
Chip Davis21d38f72020-10-13 13:20:49 -05004942 statement("#define spvImage2DAtomicCoord(tc, tex) (((((tex).get_width() + ",
4943 " spvLinearTextureAlignment / 4 - 1) & ~(",
4944 " spvLinearTextureAlignment / 4 - 1)) * (tc).y) + (tc).x)");
Bill Hollings8f6df772017-05-19 18:14:08 -04004945 statement("");
4946 break;
4947 }
4948
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004949 // "fadd" intrinsic support
Lukas Hermanns51be6012019-09-17 15:10:39 -04004950 case SPVFuncImplFAdd:
4951 statement("template<typename T>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04004952 statement("[[clang::optnone]] T spvFAdd(T l, T r)");
Lukas Hermanns51be6012019-09-17 15:10:39 -04004953 begin_scope();
4954 statement("return fma(T(1), l, r);");
4955 end_scope();
4956 statement("");
4957 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004958
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02004959 // "fsub" intrinsic support
4960 case SPVFuncImplFSub:
4961 statement("template<typename T>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04004962 statement("[[clang::optnone]] T spvFSub(T l, T r)");
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02004963 begin_scope();
4964 statement("return fma(T(-1), r, l);");
4965 end_scope();
4966 statement("");
4967 break;
4968
Lukas Hermanns50ac6862019-09-18 14:03:54 -04004969 // "fmul' intrinsic support
Lukas Hermanns51be6012019-09-17 15:10:39 -04004970 case SPVFuncImplFMul:
4971 statement("template<typename T>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04004972 statement("[[clang::optnone]] T spvFMul(T l, T r)");
Lukas Hermanns51be6012019-09-17 15:10:39 -04004973 begin_scope();
4974 statement("return fma(l, r, T(0));");
4975 end_scope();
4976 statement("");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04004977
Lukas Hermanns51be6012019-09-17 15:10:39 -04004978 statement("template<typename T, int Cols, int Rows>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04004979 statement("[[clang::optnone]] vec<T, Cols> spvFMulVectorMatrix(vec<T, Rows> v, matrix<T, Cols, Rows> m)");
Lukas Hermannsffbd8012019-10-09 11:22:25 -04004980 begin_scope();
4981 statement("vec<T, Cols> res = vec<T, Cols>(0);");
4982 statement("for (uint i = Rows; i > 0; --i)");
4983 begin_scope();
4984 statement("vec<T, Cols> tmp(0);");
4985 statement("for (uint j = 0; j < Cols; ++j)");
4986 begin_scope();
4987 statement("tmp[j] = m[j][i - 1];");
4988 end_scope();
4989 statement("res = fma(tmp, vec<T, Cols>(v[i - 1]), res);");
4990 end_scope();
4991 statement("return res;");
4992 end_scope();
4993 statement("");
4994
4995 statement("template<typename T, int Cols, int Rows>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04004996 statement("[[clang::optnone]] vec<T, Rows> spvFMulMatrixVector(matrix<T, Cols, Rows> m, vec<T, Cols> v)");
Lukas Hermanns137e9d62019-09-17 15:49:10 -04004997 begin_scope();
Lukas Hermanns51be6012019-09-17 15:10:39 -04004998 statement("vec<T, Rows> res = vec<T, Rows>(0);");
4999 statement("for (uint i = Cols; i > 0; --i)");
Lukas Hermanns137e9d62019-09-17 15:49:10 -04005000 begin_scope();
Lukas Hermanns51be6012019-09-17 15:10:39 -04005001 statement("res = fma(m[i - 1], vec<T, Rows>(v[i - 1]), res);");
Lukas Hermanns137e9d62019-09-17 15:49:10 -04005002 end_scope();
Lukas Hermanns51be6012019-09-17 15:10:39 -04005003 statement("return res;");
Lukas Hermanns137e9d62019-09-17 15:49:10 -04005004 end_scope();
Lukas Hermanns51be6012019-09-17 15:10:39 -04005005 statement("");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04005006
Lukas Hermanns51be6012019-09-17 15:10:39 -04005007 statement("template<typename T, int LCols, int LRows, int RCols, int RRows>");
Bill Hollingsfb3defc2021-09-23 14:37:08 -04005008 statement("[[clang::optnone]] matrix<T, RCols, LRows> spvFMulMatrixMatrix(matrix<T, LCols, LRows> l, matrix<T, RCols, RRows> r)");
Lukas Hermanns51be6012019-09-17 15:10:39 -04005009 begin_scope();
5010 statement("matrix<T, RCols, LRows> res;");
5011 statement("for (uint i = 0; i < RCols; i++)");
5012 begin_scope();
5013 statement("vec<T, RCols> tmp(0);");
5014 statement("for (uint j = 0; j < LCols; j++)");
5015 begin_scope();
5016 statement("tmp = fma(vec<T, RCols>(r[i][j]), l[j], tmp);");
5017 end_scope();
5018 statement("res[i] = tmp;");
5019 end_scope();
5020 statement("return res;");
5021 end_scope();
5022 statement("");
5023 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04005024
Bill Hollings57420472021-09-23 16:26:02 -04005025 case SPVFuncImplQuantizeToF16:
5026 // Ensure fast-math is disabled to match Vulkan results.
Bill Hollingsa2671e32021-09-24 14:41:15 -04005027 // SpvHalfTypeSelector is used to match the half* template type to the float* template type.
Bill Hollingsec054da2021-09-28 19:10:16 -04005028 // Depending on GPU, MSL does not always flush converted subnormal halfs to zero,
5029 // as required by OpQuantizeToF16, so check for subnormals and flush them to zero.
Bill Hollingsa2671e32021-09-24 14:41:15 -04005030 statement("template <typename F> struct SpvHalfTypeSelector;");
5031 statement("template <> struct SpvHalfTypeSelector<float> { public: using H = half; };");
Bill Hollingsba66a912021-09-25 14:36:42 -04005032 statement("template<uint N> struct SpvHalfTypeSelector<vec<float, N>> { using H = vec<half, N>; };");
Bill Hollingsa2671e32021-09-24 14:41:15 -04005033 statement("template<typename F, typename H = typename SpvHalfTypeSelector<F>::H>");
Bill Hollingsec054da2021-09-28 19:10:16 -04005034 statement("[[clang::optnone]] F spvQuantizeToF16(F fval)");
Bill Hollings57420472021-09-23 16:26:02 -04005035 begin_scope();
Bill Hollingsec054da2021-09-28 19:10:16 -04005036 statement("H hval = H(fval);");
5037 statement("hval = select(copysign(H(0), hval), hval, isnormal(hval) || isinf(hval) || isnan(hval));");
5038 statement("return F(hval);");
Bill Hollings57420472021-09-23 16:26:02 -04005039 end_scope();
5040 statement("");
5041 break;
5042
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005043 // Emulate texturecube_array with texture2d_array for iOS where this type is not available
Lukas Hermanns51be6012019-09-17 15:10:39 -04005044 case SPVFuncImplCubemapTo2DArrayFace:
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005045 statement(force_inline);
Lukas Hermanns51be6012019-09-17 15:10:39 -04005046 statement("float3 spvCubemapTo2DArrayFace(float3 P)");
5047 begin_scope();
5048 statement("float3 Coords = abs(P.xyz);");
5049 statement("float CubeFace = 0;");
5050 statement("float ProjectionAxis = 0;");
5051 statement("float u = 0;");
5052 statement("float v = 0;");
5053 statement("if (Coords.x >= Coords.y && Coords.x >= Coords.z)");
5054 begin_scope();
5055 statement("CubeFace = P.x >= 0 ? 0 : 1;");
5056 statement("ProjectionAxis = Coords.x;");
5057 statement("u = P.x >= 0 ? -P.z : P.z;");
5058 statement("v = -P.y;");
5059 end_scope();
5060 statement("else if (Coords.y >= Coords.x && Coords.y >= Coords.z)");
5061 begin_scope();
5062 statement("CubeFace = P.y >= 0 ? 2 : 3;");
5063 statement("ProjectionAxis = Coords.y;");
5064 statement("u = P.x;");
5065 statement("v = P.y >= 0 ? P.z : -P.z;");
5066 end_scope();
5067 statement("else");
5068 begin_scope();
5069 statement("CubeFace = P.z >= 0 ? 4 : 5;");
5070 statement("ProjectionAxis = Coords.z;");
5071 statement("u = P.z >= 0 ? P.x : -P.x;");
5072 statement("v = -P.y;");
5073 end_scope();
5074 statement("u = 0.5 * (u/ProjectionAxis + 1);");
5075 statement("v = 0.5 * (v/ProjectionAxis + 1);");
5076 statement("return float3(u, v, CubeFace);");
5077 end_scope();
5078 statement("");
5079 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04005080
Bill Hollings8f6df772017-05-19 18:14:08 -04005081 case SPVFuncImplInverse4x4:
5082 statement("// Returns the determinant of a 2x2 matrix.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005083 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005084 statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
Bill Hollings8f6df772017-05-19 18:14:08 -04005085 begin_scope();
5086 statement("return a1 * b2 - b1 * a2;");
5087 end_scope();
5088 statement("");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005089
Bill Hollings8f6df772017-05-19 18:14:08 -04005090 statement("// Returns the determinant of a 3x3 matrix.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005091 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005092 statement("float spvDet3x3(float a1, float a2, float a3, float b1, float b2, float b3, float c1, "
Bill Hollings8f6df772017-05-19 18:14:08 -04005093 "float c2, float c3)");
5094 begin_scope();
5095 statement("return a1 * spvDet2x2(b2, b3, c2, c3) - b1 * spvDet2x2(a2, a3, c2, c3) + c1 * spvDet2x2(a2, a3, "
5096 "b2, b3);");
5097 end_scope();
5098 statement("");
5099 statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
5100 statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005101 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005102 statement("float4x4 spvInverse4x4(float4x4 m)");
Bill Hollings8f6df772017-05-19 18:14:08 -04005103 begin_scope();
5104 statement("float4x4 adj; // The adjoint matrix (inverse after dividing by determinant)");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005105 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005106 statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
5107 statement("adj[0][0] = spvDet3x3(m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
5108 "m[3][3]);");
5109 statement("adj[0][1] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[2][1], m[2][2], m[2][3], m[3][1], m[3][2], "
5110 "m[3][3]);");
5111 statement("adj[0][2] = spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[3][1], m[3][2], "
5112 "m[3][3]);");
5113 statement("adj[0][3] = -spvDet3x3(m[0][1], m[0][2], m[0][3], m[1][1], m[1][2], m[1][3], m[2][1], m[2][2], "
5114 "m[2][3]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005115 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005116 statement("adj[1][0] = -spvDet3x3(m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
5117 "m[3][3]);");
5118 statement("adj[1][1] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[2][0], m[2][2], m[2][3], m[3][0], m[3][2], "
5119 "m[3][3]);");
5120 statement("adj[1][2] = -spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[3][0], m[3][2], "
5121 "m[3][3]);");
5122 statement("adj[1][3] = spvDet3x3(m[0][0], m[0][2], m[0][3], m[1][0], m[1][2], m[1][3], m[2][0], m[2][2], "
5123 "m[2][3]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005124 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005125 statement("adj[2][0] = spvDet3x3(m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
5126 "m[3][3]);");
5127 statement("adj[2][1] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[2][0], m[2][1], m[2][3], m[3][0], m[3][1], "
5128 "m[3][3]);");
5129 statement("adj[2][2] = spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[3][0], m[3][1], "
5130 "m[3][3]);");
5131 statement("adj[2][3] = -spvDet3x3(m[0][0], m[0][1], m[0][3], m[1][0], m[1][1], m[1][3], m[2][0], m[2][1], "
5132 "m[2][3]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005133 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005134 statement("adj[3][0] = -spvDet3x3(m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
5135 "m[3][2]);");
5136 statement("adj[3][1] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[2][0], m[2][1], m[2][2], m[3][0], m[3][1], "
5137 "m[3][2]);");
5138 statement("adj[3][2] = -spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[3][0], m[3][1], "
5139 "m[3][2]);");
5140 statement("adj[3][3] = spvDet3x3(m[0][0], m[0][1], m[0][2], m[1][0], m[1][1], m[1][2], m[2][0], m[2][1], "
5141 "m[2][2]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005142 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005143 statement("// Calculate the determinant as a combination of the cofactors of the first row.");
5144 statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]) + (adj[0][3] "
5145 "* m[3][0]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005146 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005147 statement("// Divide the classical adjoint matrix by the determinant.");
5148 statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
5149 statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
5150 end_scope();
5151 statement("");
5152 break;
5153
5154 case SPVFuncImplInverse3x3:
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005155 if (spv_function_implementations.count(SPVFuncImplInverse4x4) == 0)
5156 {
5157 statement("// Returns the determinant of a 2x2 matrix.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005158 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005159 statement("float spvDet2x2(float a1, float a2, float b1, float b2)");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005160 begin_scope();
5161 statement("return a1 * b2 - b1 * a2;");
5162 end_scope();
5163 statement("");
5164 }
5165
Bill Hollings8f6df772017-05-19 18:14:08 -04005166 statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
5167 statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005168 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005169 statement("float3x3 spvInverse3x3(float3x3 m)");
Bill Hollings8f6df772017-05-19 18:14:08 -04005170 begin_scope();
5171 statement("float3x3 adj; // The adjoint matrix (inverse after dividing by determinant)");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005172 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005173 statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
5174 statement("adj[0][0] = spvDet2x2(m[1][1], m[1][2], m[2][1], m[2][2]);");
5175 statement("adj[0][1] = -spvDet2x2(m[0][1], m[0][2], m[2][1], m[2][2]);");
5176 statement("adj[0][2] = spvDet2x2(m[0][1], m[0][2], m[1][1], m[1][2]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005177 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005178 statement("adj[1][0] = -spvDet2x2(m[1][0], m[1][2], m[2][0], m[2][2]);");
5179 statement("adj[1][1] = spvDet2x2(m[0][0], m[0][2], m[2][0], m[2][2]);");
5180 statement("adj[1][2] = -spvDet2x2(m[0][0], m[0][2], m[1][0], m[1][2]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005181 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005182 statement("adj[2][0] = spvDet2x2(m[1][0], m[1][1], m[2][0], m[2][1]);");
5183 statement("adj[2][1] = -spvDet2x2(m[0][0], m[0][1], m[2][0], m[2][1]);");
5184 statement("adj[2][2] = spvDet2x2(m[0][0], m[0][1], m[1][0], m[1][1]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005185 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005186 statement("// Calculate the determinant as a combination of the cofactors of the first row.");
5187 statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]) + (adj[0][2] * m[2][0]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005188 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005189 statement("// Divide the classical adjoint matrix by the determinant.");
5190 statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
5191 statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
5192 end_scope();
5193 statement("");
5194 break;
5195
5196 case SPVFuncImplInverse2x2:
5197 statement("// Returns the inverse of a matrix, by using the algorithm of calculating the classical");
5198 statement("// adjoint and dividing by the determinant. The contents of the matrix are changed.");
Lukas Hermanns50ac6862019-09-18 14:03:54 -04005199 statement(force_inline);
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04005200 statement("float2x2 spvInverse2x2(float2x2 m)");
Bill Hollings8f6df772017-05-19 18:14:08 -04005201 begin_scope();
5202 statement("float2x2 adj; // The adjoint matrix (inverse after dividing by determinant)");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005203 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005204 statement("// Create the transpose of the cofactors, as the classical adjoint of the matrix.");
5205 statement("adj[0][0] = m[1][1];");
5206 statement("adj[0][1] = -m[0][1];");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005207 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005208 statement("adj[1][0] = -m[1][0];");
5209 statement("adj[1][1] = m[0][0];");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005210 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005211 statement("// Calculate the determinant as a combination of the cofactors of the first row.");
5212 statement("float det = (adj[0][0] * m[0][0]) + (adj[0][1] * m[1][0]);");
Hans-Kristian Arntzen6a12ff72018-02-23 16:48:16 +01005213 statement_no_indent("");
Bill Hollings8f6df772017-05-19 18:14:08 -04005214 statement("// Divide the classical adjoint matrix by the determinant.");
5215 statement("// If determinant is zero, matrix is not invertable, so leave it unchanged.");
5216 statement("return (det != 0.0f) ? (adj * (1.0f / det)) : m;");
5217 end_scope();
5218 statement("");
5219 break;
5220
Chip Davis39dce882019-08-02 15:11:19 -05005221 case SPVFuncImplForwardArgs:
Chip Davis25833212018-09-19 20:36:33 -05005222 statement("template<typename T> struct spvRemoveReference { typedef T type; };");
5223 statement("template<typename T> struct spvRemoveReference<thread T&> { typedef T type; };");
5224 statement("template<typename T> struct spvRemoveReference<thread T&&> { typedef T type; };");
5225 statement("template<typename T> inline constexpr thread T&& spvForward(thread typename "
5226 "spvRemoveReference<T>::type& x)");
5227 begin_scope();
5228 statement("return static_cast<thread T&&>(x);");
5229 end_scope();
5230 statement("template<typename T> inline constexpr thread T&& spvForward(thread typename "
5231 "spvRemoveReference<T>::type&& x)");
5232 begin_scope();
5233 statement("return static_cast<thread T&&>(x);");
5234 end_scope();
5235 statement("");
Chip Davis39dce882019-08-02 15:11:19 -05005236 break;
5237
5238 case SPVFuncImplGetSwizzle:
5239 statement("enum class spvSwizzle : uint");
5240 begin_scope();
5241 statement("none = 0,");
5242 statement("zero,");
5243 statement("one,");
5244 statement("red,");
5245 statement("green,");
5246 statement("blue,");
5247 statement("alpha");
5248 end_scope_decl();
5249 statement("");
Chip Davis25833212018-09-19 20:36:33 -05005250 statement("template<typename T>");
Chip Davis3394f532019-01-07 11:17:12 -06005251 statement("inline T spvGetSwizzle(vec<T, 4> x, T c, spvSwizzle s)");
Chip Davis25833212018-09-19 20:36:33 -05005252 begin_scope();
5253 statement("switch (s)");
5254 begin_scope();
Chip Davis3394f532019-01-07 11:17:12 -06005255 statement("case spvSwizzle::none:");
5256 statement(" return c;");
Chip Davis25833212018-09-19 20:36:33 -05005257 statement("case spvSwizzle::zero:");
5258 statement(" return 0;");
5259 statement("case spvSwizzle::one:");
5260 statement(" return 1;");
5261 statement("case spvSwizzle::red:");
5262 statement(" return x.r;");
5263 statement("case spvSwizzle::green:");
5264 statement(" return x.g;");
5265 statement("case spvSwizzle::blue:");
5266 statement(" return x.b;");
5267 statement("case spvSwizzle::alpha:");
5268 statement(" return x.a;");
Chip Davis25833212018-09-19 20:36:33 -05005269 end_scope();
Chip Davis25833212018-09-19 20:36:33 -05005270 end_scope();
5271 statement("");
Chip Davis39dce882019-08-02 15:11:19 -05005272 break;
5273
5274 case SPVFuncImplTextureSwizzle:
Chip Davis25833212018-09-19 20:36:33 -05005275 statement("// Wrapper function that swizzles texture samples and fetches.");
5276 statement("template<typename T>");
5277 statement("inline vec<T, 4> spvTextureSwizzle(vec<T, 4> x, uint s)");
5278 begin_scope();
5279 statement("if (!s)");
5280 statement(" return x;");
Chip Davis3394f532019-01-07 11:17:12 -06005281 statement("return vec<T, 4>(spvGetSwizzle(x, x.r, spvSwizzle((s >> 0) & 0xFF)), "
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +01005282 "spvGetSwizzle(x, x.g, spvSwizzle((s >> 8) & 0xFF)), spvGetSwizzle(x, x.b, spvSwizzle((s >> 16) "
5283 "& 0xFF)), "
Chip Davis3394f532019-01-07 11:17:12 -06005284 "spvGetSwizzle(x, x.a, spvSwizzle((s >> 24) & 0xFF)));");
Chip Davis25833212018-09-19 20:36:33 -05005285 end_scope();
5286 statement("");
5287 statement("template<typename T>");
5288 statement("inline T spvTextureSwizzle(T x, uint s)");
5289 begin_scope();
5290 statement("return spvTextureSwizzle(vec<T, 4>(x, 0, 0, 1), s).x;");
5291 end_scope();
5292 statement("");
Chip Davis39dce882019-08-02 15:11:19 -05005293 break;
5294
5295 case SPVFuncImplGatherSwizzle:
Chip Davis25833212018-09-19 20:36:33 -05005296 statement("// Wrapper function that swizzles texture gathers.");
Chip Davis39dce882019-08-02 15:11:19 -05005297 statement("template<typename T, template<typename, access = access::sample, typename = void> class Tex, "
5298 "typename... Ts>");
5299 statement("inline vec<T, 4> spvGatherSwizzle(const thread Tex<T>& t, sampler s, "
5300 "uint sw, component c, Ts... params) METAL_CONST_ARG(c)");
Chip Davis25833212018-09-19 20:36:33 -05005301 begin_scope();
5302 statement("if (sw)");
5303 begin_scope();
Chip Davisc7938682018-09-21 22:50:29 -05005304 statement("switch (spvSwizzle((sw >> (uint(c) * 8)) & 0xFF))");
Chip Davis25833212018-09-19 20:36:33 -05005305 begin_scope();
5306 statement("case spvSwizzle::none:");
5307 statement(" break;");
5308 statement("case spvSwizzle::zero:");
5309 statement(" return vec<T, 4>(0, 0, 0, 0);");
5310 statement("case spvSwizzle::one:");
5311 statement(" return vec<T, 4>(1, 1, 1, 1);");
5312 statement("case spvSwizzle::red:");
5313 statement(" return t.gather(s, spvForward<Ts>(params)..., component::x);");
5314 statement("case spvSwizzle::green:");
5315 statement(" return t.gather(s, spvForward<Ts>(params)..., component::y);");
5316 statement("case spvSwizzle::blue:");
5317 statement(" return t.gather(s, spvForward<Ts>(params)..., component::z);");
5318 statement("case spvSwizzle::alpha:");
5319 statement(" return t.gather(s, spvForward<Ts>(params)..., component::w);");
5320 end_scope();
5321 end_scope();
5322 // texture::gather insists on its component parameter being a constant
5323 // expression, so we need this silly workaround just to compile the shader.
5324 statement("switch (c)");
5325 begin_scope();
5326 statement("case component::x:");
5327 statement(" return t.gather(s, spvForward<Ts>(params)..., component::x);");
5328 statement("case component::y:");
5329 statement(" return t.gather(s, spvForward<Ts>(params)..., component::y);");
5330 statement("case component::z:");
5331 statement(" return t.gather(s, spvForward<Ts>(params)..., component::z);");
5332 statement("case component::w:");
5333 statement(" return t.gather(s, spvForward<Ts>(params)..., component::w);");
5334 end_scope();
5335 end_scope();
5336 statement("");
Chip Davis39dce882019-08-02 15:11:19 -05005337 break;
5338
5339 case SPVFuncImplGatherCompareSwizzle:
Chip Davis010fecc2018-09-29 09:52:26 -05005340 statement("// Wrapper function that swizzles depth texture gathers.");
Chip Davis39dce882019-08-02 15:11:19 -05005341 statement("template<typename T, template<typename, access = access::sample, typename = void> class Tex, "
5342 "typename... Ts>");
5343 statement("inline vec<T, 4> spvGatherCompareSwizzle(const thread Tex<T>& t, sampler "
5344 "s, uint sw, Ts... params) ");
Chip Davis010fecc2018-09-29 09:52:26 -05005345 begin_scope();
5346 statement("if (sw)");
5347 begin_scope();
5348 statement("switch (spvSwizzle(sw & 0xFF))");
5349 begin_scope();
5350 statement("case spvSwizzle::none:");
5351 statement("case spvSwizzle::red:");
5352 statement(" break;");
5353 statement("case spvSwizzle::zero:");
5354 statement("case spvSwizzle::green:");
5355 statement("case spvSwizzle::blue:");
5356 statement("case spvSwizzle::alpha:");
5357 statement(" return vec<T, 4>(0, 0, 0, 0);");
5358 statement("case spvSwizzle::one:");
5359 statement(" return vec<T, 4>(1, 1, 1, 1);");
5360 end_scope();
5361 end_scope();
5362 statement("return t.gather_compare(s, spvForward<Ts>(params)...);");
5363 end_scope();
5364 statement("");
Chip Davis9d941572019-05-15 16:03:30 -05005365 break;
5366
Chip Davis1264e272020-10-21 01:51:48 -05005367 case SPVFuncImplSubgroupBroadcast:
5368 // Metal doesn't allow broadcasting boolean values directly, but we can work around that by broadcasting
5369 // them as integers.
5370 statement("template<typename T>");
5371 statement("inline T spvSubgroupBroadcast(T value, ushort lane)");
5372 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005373 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005374 statement("return quad_broadcast(value, lane);");
5375 else
5376 statement("return simd_broadcast(value, lane);");
5377 end_scope();
5378 statement("");
5379 statement("template<>");
5380 statement("inline bool spvSubgroupBroadcast(bool value, ushort lane)");
5381 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005382 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005383 statement("return !!quad_broadcast((ushort)value, lane);");
5384 else
5385 statement("return !!simd_broadcast((ushort)value, lane);");
5386 end_scope();
5387 statement("");
5388 statement("template<uint N>");
5389 statement("inline vec<bool, N> spvSubgroupBroadcast(vec<bool, N> value, ushort lane)");
5390 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005391 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005392 statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
5393 else
5394 statement("return (vec<bool, N>)simd_broadcast((vec<ushort, N>)value, lane);");
5395 end_scope();
5396 statement("");
5397 break;
5398
5399 case SPVFuncImplSubgroupBroadcastFirst:
5400 statement("template<typename T>");
5401 statement("inline T spvSubgroupBroadcastFirst(T value)");
5402 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005403 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5404 statement("return quad_broadcast_first(value);");
5405 else
5406 statement("return simd_broadcast_first(value);");
Chip Davis1264e272020-10-21 01:51:48 -05005407 end_scope();
5408 statement("");
5409 statement("template<>");
5410 statement("inline bool spvSubgroupBroadcastFirst(bool value)");
5411 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005412 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5413 statement("return !!quad_broadcast_first((ushort)value);");
5414 else
5415 statement("return !!simd_broadcast_first((ushort)value);");
Chip Davis1264e272020-10-21 01:51:48 -05005416 end_scope();
5417 statement("");
5418 statement("template<uint N>");
5419 statement("inline vec<bool, N> spvSubgroupBroadcastFirst(vec<bool, N> value)");
5420 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005421 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5422 statement("return (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value);");
5423 else
5424 statement("return (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value);");
Chip Davis1264e272020-10-21 01:51:48 -05005425 end_scope();
5426 statement("");
5427 break;
5428
Chip Davis9d941572019-05-15 16:03:30 -05005429 case SPVFuncImplSubgroupBallot:
5430 statement("inline uint4 spvSubgroupBallot(bool value)");
5431 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005432 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5433 {
5434 statement("return uint4((quad_vote::vote_t)quad_ballot(value), 0, 0, 0);");
5435 }
5436 else if (msl_options.is_ios())
5437 {
5438 // The current simd_vote on iOS uses a 32-bit integer-like object.
5439 statement("return uint4((simd_vote::vote_t)simd_ballot(value), 0, 0, 0);");
5440 }
5441 else
5442 {
5443 statement("simd_vote vote = simd_ballot(value);");
5444 statement("// simd_ballot() returns a 64-bit integer-like object, but");
5445 statement("// SPIR-V callers expect a uint4. We must convert.");
5446 statement("// FIXME: This won't include higher bits if Apple ever supports");
5447 statement("// 128 lanes in an SIMD-group.");
Chip Davis03ad13b2021-02-21 11:14:38 -06005448 statement("return uint4(as_type<uint2>((simd_vote::vote_t)vote), 0, 0);");
Chip Davis68908352020-11-18 23:16:46 -06005449 }
Chip Davis9d941572019-05-15 16:03:30 -05005450 end_scope();
5451 statement("");
5452 break;
5453
5454 case SPVFuncImplSubgroupBallotBitExtract:
5455 statement("inline bool spvSubgroupBallotBitExtract(uint4 ballot, uint bit)");
5456 begin_scope();
5457 statement("return !!extract_bits(ballot[bit / 32], bit % 32, 1);");
5458 end_scope();
5459 statement("");
5460 break;
5461
5462 case SPVFuncImplSubgroupBallotFindLSB:
Chip Davis065b5bd2020-10-20 23:59:30 -05005463 statement("inline uint spvSubgroupBallotFindLSB(uint4 ballot, uint gl_SubgroupSize)");
Chip Davis9d941572019-05-15 16:03:30 -05005464 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005465 if (msl_options.is_ios())
5466 {
5467 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
5468 }
5469 else
5470 {
5471 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
5472 "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
5473 }
Chip Davis065b5bd2020-10-20 23:59:30 -05005474 statement("ballot &= mask;");
Chip Davis9d941572019-05-15 16:03:30 -05005475 statement("return select(ctz(ballot.x), select(32 + ctz(ballot.y), select(64 + ctz(ballot.z), select(96 + "
5476 "ctz(ballot.w), uint(-1), ballot.w == 0), ballot.z == 0), ballot.y == 0), ballot.x == 0);");
5477 end_scope();
5478 statement("");
5479 break;
5480
5481 case SPVFuncImplSubgroupBallotFindMSB:
Chip Davis065b5bd2020-10-20 23:59:30 -05005482 statement("inline uint spvSubgroupBallotFindMSB(uint4 ballot, uint gl_SubgroupSize)");
Chip Davis9d941572019-05-15 16:03:30 -05005483 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005484 if (msl_options.is_ios())
5485 {
5486 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
5487 }
5488 else
5489 {
5490 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
5491 "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
5492 }
Chip Davis065b5bd2020-10-20 23:59:30 -05005493 statement("ballot &= mask;");
Chip Davis9d941572019-05-15 16:03:30 -05005494 statement("return select(128 - (clz(ballot.w) + 1), select(96 - (clz(ballot.z) + 1), select(64 - "
5495 "(clz(ballot.y) + 1), select(32 - (clz(ballot.x) + 1), uint(-1), ballot.x == 0), ballot.y == 0), "
5496 "ballot.z == 0), ballot.w == 0);");
5497 end_scope();
5498 statement("");
5499 break;
5500
5501 case SPVFuncImplSubgroupBallotBitCount:
Chip Davis065b5bd2020-10-20 23:59:30 -05005502 statement("inline uint spvPopCount4(uint4 ballot)");
Chip Davis9d941572019-05-15 16:03:30 -05005503 begin_scope();
5504 statement("return popcount(ballot.x) + popcount(ballot.y) + popcount(ballot.z) + popcount(ballot.w);");
5505 end_scope();
5506 statement("");
Chip Davis065b5bd2020-10-20 23:59:30 -05005507 statement("inline uint spvSubgroupBallotBitCount(uint4 ballot, uint gl_SubgroupSize)");
5508 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005509 if (msl_options.is_ios())
5510 {
5511 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupSize), uint3(0));");
5512 }
5513 else
5514 {
5515 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupSize, 32u)), "
5516 "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupSize - 32, 0)), uint2(0));");
5517 }
Chip Davis065b5bd2020-10-20 23:59:30 -05005518 statement("return spvPopCount4(ballot & mask);");
5519 end_scope();
5520 statement("");
Chip Davis9d941572019-05-15 16:03:30 -05005521 statement("inline uint spvSubgroupBallotInclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
5522 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005523 if (msl_options.is_ios())
5524 {
5525 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID + 1), uint3(0));");
5526 }
5527 else
5528 {
5529 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID + 1, 32u)), "
5530 "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID + 1 - 32, 0)), "
5531 "uint2(0));");
5532 }
Chip Davis065b5bd2020-10-20 23:59:30 -05005533 statement("return spvPopCount4(ballot & mask);");
Chip Davis9d941572019-05-15 16:03:30 -05005534 end_scope();
5535 statement("");
5536 statement("inline uint spvSubgroupBallotExclusiveBitCount(uint4 ballot, uint gl_SubgroupInvocationID)");
5537 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005538 if (msl_options.is_ios())
5539 {
5540 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, gl_SubgroupInvocationID), uint2(0));");
5541 }
5542 else
5543 {
5544 statement("uint4 mask = uint4(extract_bits(0xFFFFFFFF, 0, min(gl_SubgroupInvocationID, 32u)), "
5545 "extract_bits(0xFFFFFFFF, 0, (uint)max((int)gl_SubgroupInvocationID - 32, 0)), uint2(0));");
5546 }
Chip Davis065b5bd2020-10-20 23:59:30 -05005547 statement("return spvPopCount4(ballot & mask);");
Chip Davis9d941572019-05-15 16:03:30 -05005548 end_scope();
5549 statement("");
5550 break;
5551
5552 case SPVFuncImplSubgroupAllEqual:
5553 // Metal doesn't provide a function to evaluate this directly. But, we can
5554 // implement this by comparing every thread's value to one thread's value
5555 // (in this case, the value of the first active thread). Then, by the transitive
5556 // property of equality, if all comparisons return true, then they are all equal.
5557 statement("template<typename T>");
5558 statement("inline bool spvSubgroupAllEqual(T value)");
5559 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005560 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5561 statement("return quad_all(all(value == quad_broadcast_first(value)));");
5562 else
5563 statement("return simd_all(all(value == simd_broadcast_first(value)));");
Chip Davis9d941572019-05-15 16:03:30 -05005564 end_scope();
5565 statement("");
5566 statement("template<>");
5567 statement("inline bool spvSubgroupAllEqual(bool value)");
5568 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005569 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5570 statement("return quad_all(value) || !quad_any(value);");
5571 else
5572 statement("return simd_all(value) || !simd_any(value);");
Chip Davis9d941572019-05-15 16:03:30 -05005573 end_scope();
5574 statement("");
Chip Davis781367d2020-10-20 23:04:43 -05005575 statement("template<uint N>");
5576 statement("inline bool spvSubgroupAllEqual(vec<bool, N> value)");
5577 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005578 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
5579 statement("return quad_all(all(value == (vec<bool, N>)quad_broadcast_first((vec<ushort, N>)value)));");
5580 else
5581 statement("return simd_all(all(value == (vec<bool, N>)simd_broadcast_first((vec<ushort, N>)value)));");
Chip Davis781367d2020-10-20 23:04:43 -05005582 end_scope();
5583 statement("");
Chip Davis9d941572019-05-15 16:03:30 -05005584 break;
Chip Davis25833212018-09-19 20:36:33 -05005585
Chip Davis1264e272020-10-21 01:51:48 -05005586 case SPVFuncImplSubgroupShuffle:
5587 statement("template<typename T>");
5588 statement("inline T spvSubgroupShuffle(T value, ushort lane)");
5589 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005590 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005591 statement("return quad_shuffle(value, lane);");
5592 else
5593 statement("return simd_shuffle(value, lane);");
5594 end_scope();
5595 statement("");
5596 statement("template<>");
5597 statement("inline bool spvSubgroupShuffle(bool value, ushort lane)");
5598 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005599 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005600 statement("return !!quad_shuffle((ushort)value, lane);");
5601 else
5602 statement("return !!simd_shuffle((ushort)value, lane);");
5603 end_scope();
5604 statement("");
5605 statement("template<uint N>");
5606 statement("inline vec<bool, N> spvSubgroupShuffle(vec<bool, N> value, ushort lane)");
5607 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005608 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005609 statement("return (vec<bool, N>)quad_shuffle((vec<ushort, N>)value, lane);");
5610 else
5611 statement("return (vec<bool, N>)simd_shuffle((vec<ushort, N>)value, lane);");
5612 end_scope();
5613 statement("");
5614 break;
5615
5616 case SPVFuncImplSubgroupShuffleXor:
5617 statement("template<typename T>");
5618 statement("inline T spvSubgroupShuffleXor(T value, ushort mask)");
5619 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005620 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005621 statement("return quad_shuffle_xor(value, mask);");
5622 else
5623 statement("return simd_shuffle_xor(value, mask);");
5624 end_scope();
5625 statement("");
5626 statement("template<>");
5627 statement("inline bool spvSubgroupShuffleXor(bool value, ushort mask)");
5628 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005629 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005630 statement("return !!quad_shuffle_xor((ushort)value, mask);");
5631 else
5632 statement("return !!simd_shuffle_xor((ushort)value, mask);");
5633 end_scope();
5634 statement("");
5635 statement("template<uint N>");
5636 statement("inline vec<bool, N> spvSubgroupShuffleXor(vec<bool, N> value, ushort mask)");
5637 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005638 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005639 statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, mask);");
5640 else
5641 statement("return (vec<bool, N>)simd_shuffle_xor((vec<ushort, N>)value, mask);");
5642 end_scope();
5643 statement("");
5644 break;
5645
5646 case SPVFuncImplSubgroupShuffleUp:
5647 statement("template<typename T>");
5648 statement("inline T spvSubgroupShuffleUp(T value, ushort delta)");
5649 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005650 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005651 statement("return quad_shuffle_up(value, delta);");
5652 else
5653 statement("return simd_shuffle_up(value, delta);");
5654 end_scope();
5655 statement("");
5656 statement("template<>");
5657 statement("inline bool spvSubgroupShuffleUp(bool value, ushort delta)");
5658 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005659 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005660 statement("return !!quad_shuffle_up((ushort)value, delta);");
5661 else
5662 statement("return !!simd_shuffle_up((ushort)value, delta);");
5663 end_scope();
5664 statement("");
5665 statement("template<uint N>");
5666 statement("inline vec<bool, N> spvSubgroupShuffleUp(vec<bool, N> value, ushort delta)");
5667 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005668 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005669 statement("return (vec<bool, N>)quad_shuffle_up((vec<ushort, N>)value, delta);");
5670 else
5671 statement("return (vec<bool, N>)simd_shuffle_up((vec<ushort, N>)value, delta);");
5672 end_scope();
5673 statement("");
5674 break;
5675
5676 case SPVFuncImplSubgroupShuffleDown:
5677 statement("template<typename T>");
5678 statement("inline T spvSubgroupShuffleDown(T value, ushort delta)");
5679 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005680 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005681 statement("return quad_shuffle_down(value, delta);");
5682 else
5683 statement("return simd_shuffle_down(value, delta);");
5684 end_scope();
5685 statement("");
5686 statement("template<>");
5687 statement("inline bool spvSubgroupShuffleDown(bool value, ushort delta)");
5688 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005689 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005690 statement("return !!quad_shuffle_down((ushort)value, delta);");
5691 else
5692 statement("return !!simd_shuffle_down((ushort)value, delta);");
5693 end_scope();
5694 statement("");
5695 statement("template<uint N>");
5696 statement("inline vec<bool, N> spvSubgroupShuffleDown(vec<bool, N> value, ushort delta)");
5697 begin_scope();
Chip Davis68908352020-11-18 23:16:46 -06005698 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
Chip Davis1264e272020-10-21 01:51:48 -05005699 statement("return (vec<bool, N>)quad_shuffle_down((vec<ushort, N>)value, delta);");
5700 else
5701 statement("return (vec<bool, N>)simd_shuffle_down((vec<ushort, N>)value, delta);");
5702 end_scope();
5703 statement("");
5704 break;
5705
5706 case SPVFuncImplQuadBroadcast:
5707 statement("template<typename T>");
5708 statement("inline T spvQuadBroadcast(T value, uint lane)");
5709 begin_scope();
5710 statement("return quad_broadcast(value, lane);");
5711 end_scope();
5712 statement("");
5713 statement("template<>");
5714 statement("inline bool spvQuadBroadcast(bool value, uint lane)");
5715 begin_scope();
5716 statement("return !!quad_broadcast((ushort)value, lane);");
5717 end_scope();
5718 statement("");
5719 statement("template<uint N>");
5720 statement("inline vec<bool, N> spvQuadBroadcast(vec<bool, N> value, uint lane)");
5721 begin_scope();
5722 statement("return (vec<bool, N>)quad_broadcast((vec<ushort, N>)value, lane);");
5723 end_scope();
5724 statement("");
5725 break;
5726
5727 case SPVFuncImplQuadSwap:
5728 // We can implement this easily based on the following table giving
5729 // the target lane ID from the direction and current lane ID:
5730 // Direction
5731 // | 0 | 1 | 2 |
5732 // ---+---+---+---+
5733 // L 0 | 1 2 3
5734 // a 1 | 0 3 2
5735 // n 2 | 3 0 1
5736 // e 3 | 2 1 0
5737 // Notice that target = source ^ (direction + 1).
5738 statement("template<typename T>");
5739 statement("inline T spvQuadSwap(T value, uint dir)");
5740 begin_scope();
5741 statement("return quad_shuffle_xor(value, dir + 1);");
5742 end_scope();
5743 statement("");
5744 statement("template<>");
5745 statement("inline bool spvQuadSwap(bool value, uint dir)");
5746 begin_scope();
5747 statement("return !!quad_shuffle_xor((ushort)value, dir + 1);");
5748 end_scope();
5749 statement("");
5750 statement("template<uint N>");
5751 statement("inline vec<bool, N> spvQuadSwap(vec<bool, N> value, uint dir)");
5752 begin_scope();
5753 statement("return (vec<bool, N>)quad_shuffle_xor((vec<ushort, N>)value, dir + 1);");
5754 end_scope();
5755 statement("");
5756 break;
5757
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005758 case SPVFuncImplReflectScalar:
5759 // Metal does not support scalar versions of these functions.
Bill Hollings40141ff2021-09-22 18:58:31 -04005760 // Ensure fast-math is disabled to match Vulkan results.
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005761 statement("template<typename T>");
Bill Hollings40141ff2021-09-22 18:58:31 -04005762 statement("[[clang::optnone]] T spvReflect(T i, T n)");
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005763 begin_scope();
Hans-Kristian Arntzen4056d0b2019-07-03 14:32:06 +02005764 statement("return i - T(2) * i * n * n;");
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005765 end_scope();
5766 statement("");
5767 break;
5768
5769 case SPVFuncImplRefractScalar:
5770 // Metal does not support scalar versions of these functions.
5771 statement("template<typename T>");
5772 statement("inline T spvRefract(T i, T n, T eta)");
5773 begin_scope();
Hans-Kristian Arntzen4056d0b2019-07-03 14:32:06 +02005774 statement("T NoI = n * i;");
5775 statement("T NoI2 = NoI * NoI;");
5776 statement("T k = T(1) - eta * eta * (T(1) - NoI2);");
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005777 statement("if (k < T(0))");
5778 begin_scope();
5779 statement("return T(0);");
5780 end_scope();
5781 statement("else");
5782 begin_scope();
Hans-Kristian Arntzen4056d0b2019-07-03 14:32:06 +02005783 statement("return eta * i - (eta * NoI + sqrt(k)) * n;");
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02005784 end_scope();
5785 end_scope();
5786 statement("");
5787 break;
5788
Hans-Kristian Arntzenc7eda1b2019-07-17 11:24:31 +02005789 case SPVFuncImplFaceForwardScalar:
5790 // Metal does not support scalar versions of these functions.
5791 statement("template<typename T>");
5792 statement("inline T spvFaceForward(T n, T i, T nref)");
5793 begin_scope();
5794 statement("return i * nref < T(0) ? n : -n;");
5795 end_scope();
5796 statement("");
5797 break;
5798
Chip Davis39dce882019-08-02 15:11:19 -05005799 case SPVFuncImplChromaReconstructNearest2Plane:
5800 statement("template<typename T, typename... LodOptions>");
5801 statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, sampler "
5802 "samp, float2 coord, LodOptions... options)");
5803 begin_scope();
5804 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5805 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5806 statement("ycbcr.br = plane1.sample(samp, coord, spvForward<LodOptions>(options)...).rg;");
5807 statement("return ycbcr;");
5808 end_scope();
5809 statement("");
5810 break;
5811
5812 case SPVFuncImplChromaReconstructNearest3Plane:
5813 statement("template<typename T, typename... LodOptions>");
5814 statement("inline vec<T, 4> spvChromaReconstructNearest(texture2d<T> plane0, texture2d<T> plane1, "
5815 "texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
5816 begin_scope();
5817 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5818 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5819 statement("ycbcr.b = plane1.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5820 statement("ycbcr.r = plane2.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5821 statement("return ycbcr;");
5822 end_scope();
5823 statement("");
5824 break;
5825
5826 case SPVFuncImplChromaReconstructLinear422CositedEven2Plane:
5827 statement("template<typename T, typename... LodOptions>");
5828 statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
5829 "plane1, sampler samp, float2 coord, LodOptions... options)");
5830 begin_scope();
5831 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5832 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5833 statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
5834 begin_scope();
5835 statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5836 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), 0.5).rg);");
5837 end_scope();
5838 statement("else");
5839 begin_scope();
5840 statement("ycbcr.br = plane1.sample(samp, coord, spvForward<LodOptions>(options)...).rg;");
5841 end_scope();
5842 statement("return ycbcr;");
5843 end_scope();
5844 statement("");
5845 break;
5846
5847 case SPVFuncImplChromaReconstructLinear422CositedEven3Plane:
5848 statement("template<typename T, typename... LodOptions>");
5849 statement("inline vec<T, 4> spvChromaReconstructLinear422CositedEven(texture2d<T> plane0, texture2d<T> "
5850 "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
5851 begin_scope();
5852 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5853 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5854 statement("if (fract(coord.x * plane1.get_width()) != 0.0)");
5855 begin_scope();
5856 statement("ycbcr.b = T(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5857 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), 0.5).r);");
5858 statement("ycbcr.r = T(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
5859 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), 0.5).r);");
5860 end_scope();
5861 statement("else");
5862 begin_scope();
5863 statement("ycbcr.b = plane1.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5864 statement("ycbcr.r = plane2.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5865 end_scope();
5866 statement("return ycbcr;");
5867 end_scope();
5868 statement("");
5869 break;
5870
5871 case SPVFuncImplChromaReconstructLinear422Midpoint2Plane:
5872 statement("template<typename T, typename... LodOptions>");
5873 statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
5874 "plane1, sampler samp, float2 coord, LodOptions... options)");
5875 begin_scope();
5876 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5877 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5878 statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
5879 statement("ycbcr.br = vec<T, 2>(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5880 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., offs), 0.25).rg);");
5881 statement("return ycbcr;");
5882 end_scope();
5883 statement("");
5884 break;
5885
5886 case SPVFuncImplChromaReconstructLinear422Midpoint3Plane:
5887 statement("template<typename T, typename... LodOptions>");
5888 statement("inline vec<T, 4> spvChromaReconstructLinear422Midpoint(texture2d<T> plane0, texture2d<T> "
5889 "plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
5890 begin_scope();
5891 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5892 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5893 statement("int2 offs = int2(fract(coord.x * plane1.get_width()) != 0.0 ? 1 : -1, 0);");
5894 statement("ycbcr.b = T(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5895 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., offs), 0.25).r);");
5896 statement("ycbcr.r = T(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
5897 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., offs), 0.25).r);");
5898 statement("return ycbcr;");
5899 end_scope();
5900 statement("");
5901 break;
5902
5903 case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane:
5904 statement("template<typename T, typename... LodOptions>");
5905 statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
5906 "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
5907 begin_scope();
5908 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5909 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5910 statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
5911 statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5912 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5913 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5914 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).rg);");
5915 statement("return ycbcr;");
5916 end_scope();
5917 statement("");
5918 break;
5919
5920 case SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane:
5921 statement("template<typename T, typename... LodOptions>");
5922 statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYCositedEven(texture2d<T> plane0, "
5923 "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
5924 begin_scope();
5925 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5926 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5927 statement("float2 ab = fract(round(coord * float2(plane0.get_width(), plane0.get_height())) * 0.5);");
5928 statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5929 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5930 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5931 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
5932 statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
5933 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5934 "mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5935 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
5936 statement("return ycbcr;");
5937 end_scope();
5938 statement("");
5939 break;
5940
5941 case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane:
5942 statement("template<typename T, typename... LodOptions>");
5943 statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
5944 "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
5945 begin_scope();
5946 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5947 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5948 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
5949 "0)) * 0.5);");
5950 statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5951 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5952 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5953 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).rg);");
5954 statement("return ycbcr;");
5955 end_scope();
5956 statement("");
5957 break;
5958
5959 case SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane:
5960 statement("template<typename T, typename... LodOptions>");
5961 statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYCositedEven(texture2d<T> plane0, "
5962 "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
5963 begin_scope();
5964 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5965 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5966 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
5967 "0)) * 0.5);");
5968 statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5969 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5970 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5971 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
5972 statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
5973 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5974 "mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5975 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
5976 statement("return ycbcr;");
5977 end_scope();
5978 statement("");
5979 break;
5980
5981 case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane:
5982 statement("template<typename T, typename... LodOptions>");
5983 statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
5984 "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
5985 begin_scope();
5986 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
5987 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
5988 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
5989 "0.5)) * 0.5);");
5990 statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
5991 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
5992 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
5993 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).rg);");
5994 statement("return ycbcr;");
5995 end_scope();
5996 statement("");
5997 break;
5998
5999 case SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane:
6000 statement("template<typename T, typename... LodOptions>");
6001 statement("inline vec<T, 4> spvChromaReconstructLinear420XCositedEvenYMidpoint(texture2d<T> plane0, "
6002 "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
6003 begin_scope();
6004 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
6005 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
6006 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0, "
6007 "0.5)) * 0.5);");
6008 statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
6009 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
6010 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
6011 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
6012 statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
6013 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
6014 "mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
6015 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
6016 statement("return ycbcr;");
6017 end_scope();
6018 statement("");
6019 break;
6020
6021 case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane:
6022 statement("template<typename T, typename... LodOptions>");
6023 statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
6024 "texture2d<T> plane1, sampler samp, float2 coord, LodOptions... options)");
6025 begin_scope();
6026 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
6027 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
6028 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
6029 "0.5)) * 0.5);");
6030 statement("ycbcr.br = vec<T, 2>(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
6031 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
6032 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
6033 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).rg);");
6034 statement("return ycbcr;");
6035 end_scope();
6036 statement("");
6037 break;
6038
6039 case SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane:
6040 statement("template<typename T, typename... LodOptions>");
6041 statement("inline vec<T, 4> spvChromaReconstructLinear420XMidpointYMidpoint(texture2d<T> plane0, "
6042 "texture2d<T> plane1, texture2d<T> plane2, sampler samp, float2 coord, LodOptions... options)");
6043 begin_scope();
6044 statement("vec<T, 4> ycbcr = vec<T, 4>(0, 0, 0, 1);");
6045 statement("ycbcr.g = plane0.sample(samp, coord, spvForward<LodOptions>(options)...).r;");
6046 statement("float2 ab = fract((round(coord * float2(plane0.get_width(), plane0.get_height())) - float2(0.5, "
6047 "0.5)) * 0.5);");
6048 statement("ycbcr.b = T(mix(mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)...), "
6049 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
6050 "mix(plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
6051 "plane1.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
6052 statement("ycbcr.r = T(mix(mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)...), "
6053 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 0)), ab.x), "
6054 "mix(plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(0, 1)), "
6055 "plane2.sample(samp, coord, spvForward<LodOptions>(options)..., int2(1, 1)), ab.x), ab.y).r);");
6056 statement("return ycbcr;");
6057 end_scope();
6058 statement("");
6059 break;
6060
6061 case SPVFuncImplExpandITUFullRange:
6062 statement("template<typename T>");
6063 statement("inline vec<T, 4> spvExpandITUFullRange(vec<T, 4> ycbcr, int n)");
6064 begin_scope();
6065 statement("ycbcr.br -= exp2(T(n-1))/(exp2(T(n))-1);");
6066 statement("return ycbcr;");
6067 end_scope();
6068 statement("");
6069 break;
6070
6071 case SPVFuncImplExpandITUNarrowRange:
6072 statement("template<typename T>");
6073 statement("inline vec<T, 4> spvExpandITUNarrowRange(vec<T, 4> ycbcr, int n)");
6074 begin_scope();
6075 statement("ycbcr.g = (ycbcr.g * (exp2(T(n)) - 1) - ldexp(T(16), n - 8))/ldexp(T(219), n - 8);");
6076 statement("ycbcr.br = (ycbcr.br * (exp2(T(n)) - 1) - ldexp(T(128), n - 8))/ldexp(T(224), n - 8);");
6077 statement("return ycbcr;");
6078 end_scope();
6079 statement("");
6080 break;
6081
6082 case SPVFuncImplConvertYCbCrBT709:
6083 statement("// cf. Khronos Data Format Specification, section 15.1.1");
6084 statement("constant float3x3 spvBT709Factors = {{1, 1, 1}, {0, -0.13397432/0.7152, 1.8556}, {1.5748, "
6085 "-0.33480248/0.7152, 0}};");
6086 statement("");
6087 statement("template<typename T>");
6088 statement("inline vec<T, 4> spvConvertYCbCrBT709(vec<T, 4> ycbcr)");
6089 begin_scope();
6090 statement("vec<T, 4> rgba;");
6091 statement("rgba.rgb = vec<T, 3>(spvBT709Factors * ycbcr.gbr);");
6092 statement("rgba.a = ycbcr.a;");
6093 statement("return rgba;");
6094 end_scope();
6095 statement("");
6096 break;
6097
6098 case SPVFuncImplConvertYCbCrBT601:
6099 statement("// cf. Khronos Data Format Specification, section 15.1.2");
6100 statement("constant float3x3 spvBT601Factors = {{1, 1, 1}, {0, -0.202008/0.587, 1.772}, {1.402, "
6101 "-0.419198/0.587, 0}};");
6102 statement("");
6103 statement("template<typename T>");
6104 statement("inline vec<T, 4> spvConvertYCbCrBT601(vec<T, 4> ycbcr)");
6105 begin_scope();
6106 statement("vec<T, 4> rgba;");
6107 statement("rgba.rgb = vec<T, 3>(spvBT601Factors * ycbcr.gbr);");
6108 statement("rgba.a = ycbcr.a;");
6109 statement("return rgba;");
6110 end_scope();
6111 statement("");
6112 break;
6113
6114 case SPVFuncImplConvertYCbCrBT2020:
6115 statement("// cf. Khronos Data Format Specification, section 15.1.3");
6116 statement("constant float3x3 spvBT2020Factors = {{1, 1, 1}, {0, -0.11156702/0.6780, 1.8814}, {1.4746, "
6117 "-0.38737742/0.6780, 0}};");
6118 statement("");
6119 statement("template<typename T>");
6120 statement("inline vec<T, 4> spvConvertYCbCrBT2020(vec<T, 4> ycbcr)");
6121 begin_scope();
6122 statement("vec<T, 4> rgba;");
6123 statement("rgba.rgb = vec<T, 3>(spvBT2020Factors * ycbcr.gbr);");
6124 statement("rgba.a = ycbcr.a;");
6125 statement("return rgba;");
6126 end_scope();
6127 statement("");
6128 break;
6129
6130 case SPVFuncImplDynamicImageSampler:
6131 statement("enum class spvFormatResolution");
6132 begin_scope();
6133 statement("_444 = 0,");
6134 statement("_422,");
6135 statement("_420");
6136 end_scope_decl();
6137 statement("");
6138 statement("enum class spvChromaFilter");
6139 begin_scope();
6140 statement("nearest = 0,");
6141 statement("linear");
6142 end_scope_decl();
6143 statement("");
6144 statement("enum class spvXChromaLocation");
6145 begin_scope();
6146 statement("cosited_even = 0,");
6147 statement("midpoint");
6148 end_scope_decl();
6149 statement("");
6150 statement("enum class spvYChromaLocation");
6151 begin_scope();
6152 statement("cosited_even = 0,");
6153 statement("midpoint");
6154 end_scope_decl();
6155 statement("");
6156 statement("enum class spvYCbCrModelConversion");
6157 begin_scope();
6158 statement("rgb_identity = 0,");
6159 statement("ycbcr_identity,");
6160 statement("ycbcr_bt_709,");
6161 statement("ycbcr_bt_601,");
6162 statement("ycbcr_bt_2020");
6163 end_scope_decl();
6164 statement("");
6165 statement("enum class spvYCbCrRange");
6166 begin_scope();
6167 statement("itu_full = 0,");
6168 statement("itu_narrow");
6169 end_scope_decl();
6170 statement("");
6171 statement("struct spvComponentBits");
6172 begin_scope();
6173 statement("constexpr explicit spvComponentBits(int v) thread : value(v) {}");
6174 statement("uchar value : 6;");
6175 end_scope_decl();
6176 statement("// A class corresponding to metal::sampler which holds sampler");
6177 statement("// Y'CbCr conversion info.");
6178 statement("struct spvYCbCrSampler");
6179 begin_scope();
6180 statement("constexpr spvYCbCrSampler() thread : val(build()) {}");
6181 statement("template<typename... Ts>");
6182 statement("constexpr spvYCbCrSampler(Ts... t) thread : val(build(t...)) {}");
6183 statement("constexpr spvYCbCrSampler(const thread spvYCbCrSampler& s) thread = default;");
6184 statement("");
6185 statement("spvFormatResolution get_resolution() const thread");
6186 begin_scope();
6187 statement("return spvFormatResolution((val & resolution_mask) >> resolution_base);");
6188 end_scope();
6189 statement("spvChromaFilter get_chroma_filter() const thread");
6190 begin_scope();
6191 statement("return spvChromaFilter((val & chroma_filter_mask) >> chroma_filter_base);");
6192 end_scope();
6193 statement("spvXChromaLocation get_x_chroma_offset() const thread");
6194 begin_scope();
6195 statement("return spvXChromaLocation((val & x_chroma_off_mask) >> x_chroma_off_base);");
6196 end_scope();
6197 statement("spvYChromaLocation get_y_chroma_offset() const thread");
6198 begin_scope();
6199 statement("return spvYChromaLocation((val & y_chroma_off_mask) >> y_chroma_off_base);");
6200 end_scope();
6201 statement("spvYCbCrModelConversion get_ycbcr_model() const thread");
6202 begin_scope();
6203 statement("return spvYCbCrModelConversion((val & ycbcr_model_mask) >> ycbcr_model_base);");
6204 end_scope();
6205 statement("spvYCbCrRange get_ycbcr_range() const thread");
6206 begin_scope();
6207 statement("return spvYCbCrRange((val & ycbcr_range_mask) >> ycbcr_range_base);");
6208 end_scope();
6209 statement("int get_bpc() const thread { return (val & bpc_mask) >> bpc_base; }");
6210 statement("");
6211 statement("private:");
6212 statement("ushort val;");
6213 statement("");
6214 statement("constexpr static constant ushort resolution_bits = 2;");
6215 statement("constexpr static constant ushort chroma_filter_bits = 2;");
6216 statement("constexpr static constant ushort x_chroma_off_bit = 1;");
6217 statement("constexpr static constant ushort y_chroma_off_bit = 1;");
6218 statement("constexpr static constant ushort ycbcr_model_bits = 3;");
6219 statement("constexpr static constant ushort ycbcr_range_bit = 1;");
6220 statement("constexpr static constant ushort bpc_bits = 6;");
6221 statement("");
6222 statement("constexpr static constant ushort resolution_base = 0;");
6223 statement("constexpr static constant ushort chroma_filter_base = 2;");
6224 statement("constexpr static constant ushort x_chroma_off_base = 4;");
6225 statement("constexpr static constant ushort y_chroma_off_base = 5;");
6226 statement("constexpr static constant ushort ycbcr_model_base = 6;");
6227 statement("constexpr static constant ushort ycbcr_range_base = 9;");
6228 statement("constexpr static constant ushort bpc_base = 10;");
6229 statement("");
6230 statement(
6231 "constexpr static constant ushort resolution_mask = ((1 << resolution_bits) - 1) << resolution_base;");
6232 statement("constexpr static constant ushort chroma_filter_mask = ((1 << chroma_filter_bits) - 1) << "
6233 "chroma_filter_base;");
6234 statement("constexpr static constant ushort x_chroma_off_mask = ((1 << x_chroma_off_bit) - 1) << "
6235 "x_chroma_off_base;");
6236 statement("constexpr static constant ushort y_chroma_off_mask = ((1 << y_chroma_off_bit) - 1) << "
6237 "y_chroma_off_base;");
6238 statement("constexpr static constant ushort ycbcr_model_mask = ((1 << ycbcr_model_bits) - 1) << "
6239 "ycbcr_model_base;");
6240 statement("constexpr static constant ushort ycbcr_range_mask = ((1 << ycbcr_range_bit) - 1) << "
6241 "ycbcr_range_base;");
6242 statement("constexpr static constant ushort bpc_mask = ((1 << bpc_bits) - 1) << bpc_base;");
6243 statement("");
6244 statement("static constexpr ushort build()");
6245 begin_scope();
6246 statement("return 0;");
6247 end_scope();
6248 statement("");
6249 statement("template<typename... Ts>");
6250 statement("static constexpr ushort build(spvFormatResolution res, Ts... t)");
6251 begin_scope();
6252 statement("return (ushort(res) << resolution_base) | (build(t...) & ~resolution_mask);");
6253 end_scope();
6254 statement("");
6255 statement("template<typename... Ts>");
6256 statement("static constexpr ushort build(spvChromaFilter filt, Ts... t)");
6257 begin_scope();
6258 statement("return (ushort(filt) << chroma_filter_base) | (build(t...) & ~chroma_filter_mask);");
6259 end_scope();
6260 statement("");
6261 statement("template<typename... Ts>");
6262 statement("static constexpr ushort build(spvXChromaLocation loc, Ts... t)");
6263 begin_scope();
6264 statement("return (ushort(loc) << x_chroma_off_base) | (build(t...) & ~x_chroma_off_mask);");
6265 end_scope();
6266 statement("");
6267 statement("template<typename... Ts>");
6268 statement("static constexpr ushort build(spvYChromaLocation loc, Ts... t)");
6269 begin_scope();
6270 statement("return (ushort(loc) << y_chroma_off_base) | (build(t...) & ~y_chroma_off_mask);");
6271 end_scope();
6272 statement("");
6273 statement("template<typename... Ts>");
6274 statement("static constexpr ushort build(spvYCbCrModelConversion model, Ts... t)");
6275 begin_scope();
6276 statement("return (ushort(model) << ycbcr_model_base) | (build(t...) & ~ycbcr_model_mask);");
6277 end_scope();
6278 statement("");
6279 statement("template<typename... Ts>");
6280 statement("static constexpr ushort build(spvYCbCrRange range, Ts... t)");
6281 begin_scope();
6282 statement("return (ushort(range) << ycbcr_range_base) | (build(t...) & ~ycbcr_range_mask);");
6283 end_scope();
6284 statement("");
6285 statement("template<typename... Ts>");
6286 statement("static constexpr ushort build(spvComponentBits bpc, Ts... t)");
6287 begin_scope();
6288 statement("return (ushort(bpc.value) << bpc_base) | (build(t...) & ~bpc_mask);");
6289 end_scope();
6290 end_scope_decl();
6291 statement("");
6292 statement("// A class which can hold up to three textures and a sampler, including");
6293 statement("// Y'CbCr conversion info, used to pass combined image-samplers");
6294 statement("// dynamically to functions.");
6295 statement("template<typename T>");
6296 statement("struct spvDynamicImageSampler");
6297 begin_scope();
6298 statement("texture2d<T> plane0;");
6299 statement("texture2d<T> plane1;");
6300 statement("texture2d<T> plane2;");
6301 statement("sampler samp;");
6302 statement("spvYCbCrSampler ycbcr_samp;");
6303 statement("uint swizzle = 0;");
6304 statement("");
6305 if (msl_options.swizzle_texture_samples)
6306 {
6307 statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, uint sw) thread :");
6308 statement(" plane0(tex), samp(samp), swizzle(sw) {}");
6309 }
6310 else
6311 {
6312 statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp) thread :");
6313 statement(" plane0(tex), samp(samp) {}");
6314 }
6315 statement("constexpr spvDynamicImageSampler(texture2d<T> tex, sampler samp, spvYCbCrSampler ycbcr_samp, "
6316 "uint sw) thread :");
6317 statement(" plane0(tex), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
6318 statement("constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1,");
6319 statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
6320 statement(" plane0(plane0), plane1(plane1), samp(samp), ycbcr_samp(ycbcr_samp), swizzle(sw) {}");
6321 statement(
6322 "constexpr spvDynamicImageSampler(texture2d<T> plane0, texture2d<T> plane1, texture2d<T> plane2,");
6323 statement(" sampler samp, spvYCbCrSampler ycbcr_samp, uint sw) thread :");
6324 statement(" plane0(plane0), plane1(plane1), plane2(plane2), samp(samp), ycbcr_samp(ycbcr_samp), "
6325 "swizzle(sw) {}");
6326 statement("");
6327 // XXX This is really hard to follow... I've left comments to make it a bit easier.
6328 statement("template<typename... LodOptions>");
6329 statement("vec<T, 4> do_sample(float2 coord, LodOptions... options) const thread");
6330 begin_scope();
6331 statement("if (!is_null_texture(plane1))");
6332 begin_scope();
6333 statement("if (ycbcr_samp.get_resolution() == spvFormatResolution::_444 ||");
6334 statement(" ycbcr_samp.get_chroma_filter() == spvChromaFilter::nearest)");
6335 begin_scope();
6336 statement("if (!is_null_texture(plane2))");
6337 statement(" return spvChromaReconstructNearest(plane0, plane1, plane2, samp, coord,");
6338 statement(" spvForward<LodOptions>(options)...);");
6339 statement(
6340 "return spvChromaReconstructNearest(plane0, plane1, samp, coord, spvForward<LodOptions>(options)...);");
6341 end_scope(); // if (resolution == 422 || chroma_filter == nearest)
6342 statement("switch (ycbcr_samp.get_resolution())");
6343 begin_scope();
6344 statement("case spvFormatResolution::_444: break;");
6345 statement("case spvFormatResolution::_422:");
6346 begin_scope();
6347 statement("switch (ycbcr_samp.get_x_chroma_offset())");
6348 begin_scope();
6349 statement("case spvXChromaLocation::cosited_even:");
6350 statement(" if (!is_null_texture(plane2))");
6351 statement(" return spvChromaReconstructLinear422CositedEven(");
6352 statement(" plane0, plane1, plane2, samp,");
6353 statement(" coord, spvForward<LodOptions>(options)...);");
6354 statement(" return spvChromaReconstructLinear422CositedEven(");
6355 statement(" plane0, plane1, samp, coord,");
6356 statement(" spvForward<LodOptions>(options)...);");
6357 statement("case spvXChromaLocation::midpoint:");
6358 statement(" if (!is_null_texture(plane2))");
6359 statement(" return spvChromaReconstructLinear422Midpoint(");
6360 statement(" plane0, plane1, plane2, samp,");
6361 statement(" coord, spvForward<LodOptions>(options)...);");
6362 statement(" return spvChromaReconstructLinear422Midpoint(");
6363 statement(" plane0, plane1, samp, coord,");
6364 statement(" spvForward<LodOptions>(options)...);");
6365 end_scope(); // switch (x_chroma_offset)
6366 end_scope(); // case 422:
6367 statement("case spvFormatResolution::_420:");
6368 begin_scope();
6369 statement("switch (ycbcr_samp.get_x_chroma_offset())");
6370 begin_scope();
6371 statement("case spvXChromaLocation::cosited_even:");
6372 begin_scope();
6373 statement("switch (ycbcr_samp.get_y_chroma_offset())");
6374 begin_scope();
6375 statement("case spvYChromaLocation::cosited_even:");
6376 statement(" if (!is_null_texture(plane2))");
6377 statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
6378 statement(" plane0, plane1, plane2, samp,");
6379 statement(" coord, spvForward<LodOptions>(options)...);");
6380 statement(" return spvChromaReconstructLinear420XCositedEvenYCositedEven(");
6381 statement(" plane0, plane1, samp, coord,");
6382 statement(" spvForward<LodOptions>(options)...);");
6383 statement("case spvYChromaLocation::midpoint:");
6384 statement(" if (!is_null_texture(plane2))");
6385 statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
6386 statement(" plane0, plane1, plane2, samp,");
6387 statement(" coord, spvForward<LodOptions>(options)...);");
6388 statement(" return spvChromaReconstructLinear420XCositedEvenYMidpoint(");
6389 statement(" plane0, plane1, samp, coord,");
6390 statement(" spvForward<LodOptions>(options)...);");
6391 end_scope(); // switch (y_chroma_offset)
6392 end_scope(); // case x::cosited_even:
6393 statement("case spvXChromaLocation::midpoint:");
6394 begin_scope();
6395 statement("switch (ycbcr_samp.get_y_chroma_offset())");
6396 begin_scope();
6397 statement("case spvYChromaLocation::cosited_even:");
6398 statement(" if (!is_null_texture(plane2))");
6399 statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
6400 statement(" plane0, plane1, plane2, samp,");
6401 statement(" coord, spvForward<LodOptions>(options)...);");
6402 statement(" return spvChromaReconstructLinear420XMidpointYCositedEven(");
6403 statement(" plane0, plane1, samp, coord,");
6404 statement(" spvForward<LodOptions>(options)...);");
6405 statement("case spvYChromaLocation::midpoint:");
6406 statement(" if (!is_null_texture(plane2))");
6407 statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
6408 statement(" plane0, plane1, plane2, samp,");
6409 statement(" coord, spvForward<LodOptions>(options)...);");
6410 statement(" return spvChromaReconstructLinear420XMidpointYMidpoint(");
6411 statement(" plane0, plane1, samp, coord,");
6412 statement(" spvForward<LodOptions>(options)...);");
6413 end_scope(); // switch (y_chroma_offset)
6414 end_scope(); // case x::midpoint
6415 end_scope(); // switch (x_chroma_offset)
6416 end_scope(); // case 420:
6417 end_scope(); // switch (resolution)
6418 end_scope(); // if (multiplanar)
6419 statement("return plane0.sample(samp, coord, spvForward<LodOptions>(options)...);");
6420 end_scope(); // do_sample()
6421 statement("template <typename... LodOptions>");
6422 statement("vec<T, 4> sample(float2 coord, LodOptions... options) const thread");
6423 begin_scope();
6424 statement(
6425 "vec<T, 4> s = spvTextureSwizzle(do_sample(coord, spvForward<LodOptions>(options)...), swizzle);");
6426 statement("if (ycbcr_samp.get_ycbcr_model() == spvYCbCrModelConversion::rgb_identity)");
6427 statement(" return s;");
6428 statement("");
6429 statement("switch (ycbcr_samp.get_ycbcr_range())");
6430 begin_scope();
6431 statement("case spvYCbCrRange::itu_full:");
6432 statement(" s = spvExpandITUFullRange(s, ycbcr_samp.get_bpc());");
6433 statement(" break;");
6434 statement("case spvYCbCrRange::itu_narrow:");
6435 statement(" s = spvExpandITUNarrowRange(s, ycbcr_samp.get_bpc());");
6436 statement(" break;");
6437 end_scope();
6438 statement("");
6439 statement("switch (ycbcr_samp.get_ycbcr_model())");
6440 begin_scope();
6441 statement("case spvYCbCrModelConversion::rgb_identity:"); // Silence Clang warning
6442 statement("case spvYCbCrModelConversion::ycbcr_identity:");
6443 statement(" return s;");
6444 statement("case spvYCbCrModelConversion::ycbcr_bt_709:");
6445 statement(" return spvConvertYCbCrBT709(s);");
6446 statement("case spvYCbCrModelConversion::ycbcr_bt_601:");
6447 statement(" return spvConvertYCbCrBT601(s);");
6448 statement("case spvYCbCrModelConversion::ycbcr_bt_2020:");
6449 statement(" return spvConvertYCbCrBT2020(s);");
6450 end_scope();
6451 end_scope();
6452 statement("");
6453 // Sampler Y'CbCr conversion forbids offsets.
6454 statement("vec<T, 4> sample(float2 coord, int2 offset) const thread");
6455 begin_scope();
6456 if (msl_options.swizzle_texture_samples)
6457 statement("return spvTextureSwizzle(plane0.sample(samp, coord, offset), swizzle);");
6458 else
6459 statement("return plane0.sample(samp, coord, offset);");
6460 end_scope();
6461 statement("template<typename lod_options>");
6462 statement("vec<T, 4> sample(float2 coord, lod_options options, int2 offset) const thread");
6463 begin_scope();
6464 if (msl_options.swizzle_texture_samples)
6465 statement("return spvTextureSwizzle(plane0.sample(samp, coord, options, offset), swizzle);");
6466 else
6467 statement("return plane0.sample(samp, coord, options, offset);");
6468 end_scope();
6469 statement("#if __HAVE_MIN_LOD_CLAMP__");
6470 statement("vec<T, 4> sample(float2 coord, bias b, min_lod_clamp min_lod, int2 offset) const thread");
6471 begin_scope();
6472 statement("return plane0.sample(samp, coord, b, min_lod, offset);");
6473 end_scope();
6474 statement(
6475 "vec<T, 4> sample(float2 coord, gradient2d grad, min_lod_clamp min_lod, int2 offset) const thread");
6476 begin_scope();
6477 statement("return plane0.sample(samp, coord, grad, min_lod, offset);");
6478 end_scope();
6479 statement("#endif");
6480 statement("");
6481 // Y'CbCr conversion forbids all operations but sampling.
6482 statement("vec<T, 4> read(uint2 coord, uint lod = 0) const thread");
6483 begin_scope();
6484 statement("return plane0.read(coord, lod);");
6485 end_scope();
6486 statement("");
6487 statement("vec<T, 4> gather(float2 coord, int2 offset = int2(0), component c = component::x) const thread");
6488 begin_scope();
6489 if (msl_options.swizzle_texture_samples)
6490 statement("return spvGatherSwizzle(plane0, samp, swizzle, c, coord, offset);");
6491 else
6492 statement("return plane0.gather(samp, coord, offset, c);");
6493 end_scope();
6494 end_scope_decl();
6495 statement("");
6496
Bill Hollings1a5dc0e2016-12-18 21:42:10 -05006497 default:
6498 break;
6499 }
6500 }
6501}
6502
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01006503static string inject_top_level_storage_qualifier(const string &expr, const string &qualifier)
6504{
6505 // Easier to do this through text munging since the qualifier does not exist in the type system at all,
6506 // and plumbing in all that information is not very helpful.
6507 size_t last_reference = expr.find_last_of('&');
6508 size_t last_pointer = expr.find_last_of('*');
6509 size_t last_significant = string::npos;
6510
6511 if (last_reference == string::npos)
6512 last_significant = last_pointer;
6513 else if (last_pointer == string::npos)
6514 last_significant = last_reference;
6515 else
6516 last_significant = std::max(last_reference, last_pointer);
6517
6518 if (last_significant == string::npos)
6519 return join(qualifier, " ", expr);
6520 else
6521 {
6522 return join(expr.substr(0, last_significant + 1), " ",
6523 qualifier, expr.substr(last_significant + 1, string::npos));
6524 }
6525}
6526
Bill Hollingse83e2b22017-11-15 22:44:42 -05006527// Undefined global memory is not allowed in MSL.
Bill Hollingsc93d44b2017-11-30 15:03:27 -05006528// Declare constant and init to zeros. Use {}, as global constructors can break Metal.
Bill Hollingse83e2b22017-11-15 22:44:42 -05006529void CompilerMSL::declare_undefined_values()
6530{
6531 bool emitted = false;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006532 ir.for_each_typed_id<SPIRUndef>([&](uint32_t, SPIRUndef &undef) {
Hans-Kristian Arntzen2fb9aa22019-01-11 09:29:28 +01006533 auto &type = this->get<SPIRType>(undef.basetype);
Hans-Kristian Arntzen18d03b32020-09-04 09:29:44 +02006534 // OpUndef can be void for some reason ...
6535 if (type.basetype == SPIRType::Void)
6536 return;
6537
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01006538 statement(inject_top_level_storage_qualifier(
6539 variable_decl(type, to_name(undef.self), undef.self),
6540 "constant"),
6541 " = {};");
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006542 emitted = true;
6543 });
Bill Hollingse83e2b22017-11-15 22:44:42 -05006544
6545 if (emitted)
6546 statement("");
6547}
6548
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006549void CompilerMSL::declare_constant_arrays()
6550{
Hans-Kristian Arntzendb55d472019-10-24 11:12:01 +02006551 bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
6552
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006553 // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
6554 // global constants directly, so we are able to use constants as variable expressions.
6555 bool emitted = false;
6556
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006557 ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
6558 if (c.specialization)
6559 return;
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006560
Hans-Kristian Arntzen2fb9aa22019-01-11 09:29:28 +01006561 auto &type = this->get<SPIRType>(c.constant_type);
Hans-Kristian Arntzendb55d472019-10-24 11:12:01 +02006562 // Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries.
6563 // FIXME: However, hoisting constants to main() means we need to pass down constant arrays to leaf functions if they are used there.
6564 // If there are multiple functions in the module, drop this case to avoid breaking use cases which do not need to
6565 // link into Metal libraries. This is hacky.
6566 if (!type.array.empty() && (!fully_inlined || is_scalar(type) || is_vector(type)))
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006567 {
6568 auto name = to_name(c.self);
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +01006569 statement(inject_top_level_storage_qualifier(variable_decl(type, name), "constant"),
6570 " = ", constant_expression(c), ";");
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006571 emitted = true;
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006572 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006573 });
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006574
6575 if (emitted)
6576 statement("");
6577}
6578
Lukas Hermanns50ac6862019-09-18 14:03:54 -04006579// Constant arrays of non-primitive types (i.e. matrices) won't link properly into Metal libraries
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006580void CompilerMSL::declare_complex_constant_arrays()
6581{
Hans-Kristian Arntzendb55d472019-10-24 11:12:01 +02006582 // If we do not have a fully inlined module, we did not opt in to
6583 // declaring constant arrays of complex types. See CompilerMSL::declare_constant_arrays().
6584 bool fully_inlined = ir.ids_for_type[TypeFunction].size() == 1;
6585 if (!fully_inlined)
6586 return;
6587
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006588 // MSL cannot declare arrays inline (except when declaring a variable), so we must move them out to
6589 // global constants directly, so we are able to use constants as variable expressions.
6590 bool emitted = false;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04006591
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006592 ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
6593 if (c.specialization)
6594 return;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04006595
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006596 auto &type = this->get<SPIRType>(c.constant_type);
6597 if (!type.array.empty() && !(is_scalar(type) || is_vector(type)))
6598 {
6599 auto name = to_name(c.self);
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04006600 statement("", variable_decl(type, name), " = ", constant_expression(c), ";");
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006601 emitted = true;
6602 }
6603 });
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04006604
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006605 if (emitted)
6606 statement("");
6607}
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04006608
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02006609void CompilerMSL::emit_resources()
6610{
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01006611 declare_constant_arrays();
Bill Hollingse83e2b22017-11-15 22:44:42 -05006612 declare_undefined_values();
6613
Hans-Kristian Arntzend3100602018-09-13 14:42:05 +02006614 // Emit the special [[stage_in]] and [[stage_out]] interface blocks which we created.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02006615 emit_interface_block(stage_out_var_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -06006616 emit_interface_block(patch_stage_out_var_id);
Bill Hollings9b4defe2018-06-12 11:41:35 -04006617 emit_interface_block(stage_in_var_id);
Chip Davise75add42019-02-05 18:13:26 -06006618 emit_interface_block(patch_stage_in_var_id);
Bill Hollings103aabf2016-04-06 17:42:27 -04006619}
6620
Bill Hollings1f838562017-06-15 15:24:22 -04006621// Emit declarations for the specialization Metal function constants
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006622void CompilerMSL::emit_specialization_constants_and_structs()
Bill Hollings1f838562017-06-15 15:24:22 -04006623{
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006624 SpecializationConstant wg_x, wg_y, wg_z;
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02006625 ID workgroup_size_id = get_work_group_size_specialization_constants(wg_x, wg_y, wg_z);
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006626 bool emitted = false;
Bill Hollings1f838562017-06-15 15:24:22 -04006627
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006628 unordered_set<uint32_t> declared_structs;
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02006629 unordered_set<uint32_t> aligned_structs;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006630
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02006631 // First, we need to deal with scalar block layout.
6632 // It is possible that a struct may have to be placed at an alignment which does not match the innate alignment of the struct itself.
6633 // In that case, if such a case exists for a struct, we must force that all elements of the struct become packed_ types.
6634 // This makes the struct alignment as small as physically possible.
6635 // When we actually align the struct later, we can insert padding as necessary to make the packed members behave like normally aligned types.
6636 ir.for_each_typed_id<SPIRType>([&](uint32_t type_id, const SPIRType &type) {
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +02006637 if (type.basetype == SPIRType::Struct &&
6638 has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
Hans-Kristian Arntzene90d8162019-07-19 14:18:14 +02006639 mark_scalar_layout_structs(type);
6640 });
6641
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01006642 bool builtin_block_type_is_required = false;
6643 // Very special case. If gl_PerVertex is initialized as an array (tessellation)
6644 // we have to potentially emit the gl_PerVertex struct type so that we can emit a constant LUT.
6645 ir.for_each_typed_id<SPIRConstant>([&](uint32_t, SPIRConstant &c) {
6646 auto &type = this->get<SPIRType>(c.constant_type);
6647 if (is_array(type) && has_decoration(type.self, DecorationBlock) && is_builtin_type(type))
6648 builtin_block_type_is_required = true;
6649 });
6650
Hans-Kristian Arntzendd7ebaf2019-07-18 17:05:28 +02006651 // Very particular use of the soft loop lock.
6652 // align_struct may need to create custom types on the fly, but we don't care about
6653 // these types for purpose of iterating over them in ir.ids_for_type and friends.
6654 auto loop_lock = ir.create_loop_soft_lock();
6655
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006656 for (auto &id_ : ir.ids_for_constant_or_type)
Bill Hollings1f838562017-06-15 15:24:22 -04006657 {
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006658 auto &id = ir.ids[id_];
6659
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006660 if (id.get_type() == TypeConstant)
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006661 {
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006662 auto &c = id.get<SPIRConstant>();
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006663
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006664 if (c.self == workgroup_size_id)
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006665 {
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006666 // TODO: This can be expressed as a [[threads_per_threadgroup]] input semantic, but we need to know
6667 // the work group size at compile time in SPIR-V, and [[threads_per_threadgroup]] would need to be passed around as a global.
6668 // The work group size may be a specialization constant.
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02006669 statement("constant uint3 ", builtin_to_glsl(BuiltInWorkgroupSize, StorageClassWorkgroup),
6670 " [[maybe_unused]] = ", constant_expression(get<SPIRConstant>(workgroup_size_id)), ";");
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006671 emitted = true;
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006672 }
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006673 else if (c.specialization)
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006674 {
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006675 auto &type = get<SPIRType>(c.constant_type);
6676 string sc_type_name = type_to_glsl(type);
6677 string sc_name = to_name(c.self);
6678 string sc_tmp_name = sc_name + "_tmp";
6679
6680 // Function constants are only supported in MSL 1.2 and later.
6681 // If we don't support it just declare the "default" directly.
6682 // This "default" value can be overridden to the true specialization constant by the API user.
6683 // Specialization constants which are used as array length expressions cannot be function constants in MSL,
6684 // so just fall back to macros.
Hans-Kristian Arntzen6e99fcf2018-11-01 11:23:33 +01006685 if (msl_options.supports_msl_version(1, 2) && has_decoration(c.self, DecorationSpecId) &&
6686 !c.is_used_as_array_length)
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006687 {
6688 uint32_t constant_id = get_decoration(c.self, DecorationSpecId);
6689 // Only scalar, non-composite values can be function constants.
6690 statement("constant ", sc_type_name, " ", sc_tmp_name, " [[function_constant(", constant_id,
6691 ")]];");
6692 statement("constant ", sc_type_name, " ", sc_name, " = is_function_constant_defined(", sc_tmp_name,
6693 ") ? ", sc_tmp_name, " : ", constant_expression(c), ";");
6694 }
6695 else if (has_decoration(c.self, DecorationSpecId))
6696 {
6697 // Fallback to macro overrides.
6698 c.specialization_constant_macro_name =
Hans-Kristian Arntzen6e99fcf2018-11-01 11:23:33 +01006699 constant_value_macro_name(get_decoration(c.self, DecorationSpecId));
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006700
6701 statement("#ifndef ", c.specialization_constant_macro_name);
6702 statement("#define ", c.specialization_constant_macro_name, " ", constant_expression(c));
6703 statement("#endif");
Hans-Kristian Arntzen6e99fcf2018-11-01 11:23:33 +01006704 statement("constant ", sc_type_name, " ", sc_name, " = ", c.specialization_constant_macro_name,
6705 ";");
Hans-Kristian Arntzen62db5352018-11-01 11:22:14 +01006706 }
6707 else
6708 {
6709 // Composite specialization constants must be built from other specialization constants.
6710 statement("constant ", sc_type_name, " ", sc_name, " = ", constant_expression(c), ";");
6711 }
6712 emitted = true;
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006713 }
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006714 }
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006715 else if (id.get_type() == TypeConstantOp)
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006716 {
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006717 auto &c = id.get<SPIRConstantOp>();
6718 auto &type = get<SPIRType>(c.basetype);
6719 auto name = to_name(c.self);
6720 statement("constant ", variable_decl(type, name), " = ", constant_op_expression(c), ";");
6721 emitted = true;
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006722 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006723 else if (id.get_type() == TypeType)
6724 {
6725 // Output non-builtin interface structs. These include local function structs
6726 // and structs nested within uniform and read-write buffers.
6727 auto &type = id.get<SPIRType>();
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02006728 TypeID type_id = type.self;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006729
Chip Davis688c5fc2020-02-20 21:38:28 -06006730 bool is_struct = (type.basetype == SPIRType::Struct) && type.array.empty() && !type.pointer;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006731 bool is_block =
6732 has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
6733
6734 bool is_builtin_block = is_block && is_builtin_type(type);
Hans-Kristian Arntzendf4f8ef2021-01-05 13:57:15 +01006735 bool is_declarable_struct = is_struct && (!is_builtin_block || builtin_block_type_is_required);
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006736
6737 // We'll declare this later.
Chip Daviseb89c3a2019-02-03 23:58:46 -06006738 if (stage_out_var_id && get_stage_out_struct_type().self == type_id)
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006739 is_declarable_struct = false;
Chip Daviseb89c3a2019-02-03 23:58:46 -06006740 if (patch_stage_out_var_id && get_patch_stage_out_struct_type().self == type_id)
6741 is_declarable_struct = false;
6742 if (stage_in_var_id && get_stage_in_struct_type().self == type_id)
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006743 is_declarable_struct = false;
Chip Davise75add42019-02-05 18:13:26 -06006744 if (patch_stage_in_var_id && get_patch_stage_in_struct_type().self == type_id)
6745 is_declarable_struct = false;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006746
Hans-Kristian Arntzenff3f5bc2021-04-07 14:35:00 +02006747 // Special case. Declare builtin struct anyways if we need to emit a threadgroup version of it.
Hans-Kristian Arntzen5e9c2d02021-04-09 14:59:45 +02006748 if (stage_out_masked_builtin_type_id == type_id)
Hans-Kristian Arntzenff3f5bc2021-04-07 14:35:00 +02006749 is_declarable_struct = true;
6750
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006751 // Align and emit declarable structs...but avoid declaring each more than once.
6752 if (is_declarable_struct && declared_structs.count(type_id) == 0)
6753 {
6754 if (emitted)
6755 statement("");
6756 emitted = false;
6757
6758 declared_structs.insert(type_id);
6759
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02006760 if (has_extended_decoration(type_id, SPIRVCrossDecorationBufferBlockRepacked))
6761 align_struct(type, aligned_structs);
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +01006762
6763 // Make sure we declare the underlying struct type, and not the "decorated" type with pointers, etc.
6764 emit_struct(get<SPIRType>(type_id));
6765 }
6766 }
Bill Hollings1f838562017-06-15 15:24:22 -04006767 }
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006768
Hans-Kristian Arntzen991b6552018-05-15 14:20:16 +02006769 if (emitted)
Hans-Kristian Arntzen84f8c992017-09-29 10:13:45 +02006770 statement("");
Bill Hollings1f838562017-06-15 15:24:22 -04006771}
6772
Chip Davisd3233692018-08-31 13:46:02 -05006773void CompilerMSL::emit_binary_unord_op(uint32_t result_type, uint32_t result_id, uint32_t op0, uint32_t op1,
6774 const char *op)
6775{
6776 bool forward = should_forward(op0) && should_forward(op1);
6777 emit_op(result_type, result_id,
6778 join("(isunordered(", to_enclosed_unpacked_expression(op0), ", ", to_enclosed_unpacked_expression(op1),
6779 ") || ", to_enclosed_unpacked_expression(op0), " ", op, " ", to_enclosed_unpacked_expression(op1),
6780 ")"),
6781 forward);
6782
6783 inherit_expression_dependencies(result_id, op0);
6784 inherit_expression_dependencies(result_id, op1);
6785}
6786
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006787bool CompilerMSL::emit_tessellation_io_load(uint32_t result_type_id, uint32_t id, uint32_t ptr)
6788{
6789 auto &ptr_type = expression_type(ptr);
6790 auto &result_type = get<SPIRType>(result_type_id);
6791 if (ptr_type.storage != StorageClassInput && ptr_type.storage != StorageClassOutput)
6792 return false;
6793 if (ptr_type.storage == StorageClassOutput && get_execution_model() == ExecutionModelTessellationEvaluation)
6794 return false;
6795
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006796 if (has_decoration(ptr, DecorationPatch))
6797 return false;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006798 bool ptr_is_io_variable = ir.ids[ptr].get_type() == TypeVariable;
6799
6800 bool flattened_io = variable_storage_requires_stage_io(ptr_type.storage);
6801
6802 bool flat_data_type = flattened_io &&
6803 (is_matrix(result_type) || is_array(result_type) || result_type.basetype == SPIRType::Struct);
6804
6805 // Edge case, even with multi-patch workgroups, we still need to unroll load
6806 // if we're loading control points directly.
6807 if (ptr_is_io_variable && is_array(result_type))
6808 flat_data_type = true;
6809
6810 if (!flat_data_type)
6811 return false;
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006812
6813 // Now, we must unflatten a composite type and take care of interleaving array access with gl_in/gl_out.
6814 // Lots of painful code duplication since we *really* should not unroll these kinds of loads in entry point fixup
6815 // unless we're forced to do this when the code is emitting inoptimal OpLoads.
6816 string expr;
6817
6818 uint32_t interface_index = get_extended_decoration(ptr, SPIRVCrossDecorationInterfaceMemberIndex);
6819 auto *var = maybe_get_backing_variable(ptr);
Chip Davis688c5fc2020-02-20 21:38:28 -06006820 auto &expr_type = get_pointee_type(ptr_type.self);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006821
6822 const auto &iface_type = expression_type(stage_in_ptr_var_id);
6823
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006824 if (!flattened_io)
6825 {
6826 // Simplest case for multi-patch workgroups, just unroll array as-is.
6827 if (interface_index == uint32_t(-1))
6828 return false;
6829
6830 expr += type_to_glsl(result_type) + "({ ";
6831 uint32_t num_control_points = to_array_size_literal(result_type, uint32_t(result_type.array.size()) - 1);
6832
6833 for (uint32_t i = 0; i < num_control_points; i++)
6834 {
6835 const uint32_t indices[2] = { i, interface_index };
6836 AccessChainMeta meta;
6837 expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
6838 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
6839 if (i + 1 < num_control_points)
6840 expr += ", ";
6841 }
6842 expr += " })";
6843 }
6844 else if (result_type.array.size() > 2)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006845 {
6846 SPIRV_CROSS_THROW("Cannot load tessellation IO variables with more than 2 dimensions.");
6847 }
6848 else if (result_type.array.size() == 2)
6849 {
6850 if (!ptr_is_io_variable)
6851 SPIRV_CROSS_THROW("Loading an array-of-array must be loaded directly from an IO variable.");
6852 if (interface_index == uint32_t(-1))
6853 SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006854 if (result_type.basetype == SPIRType::Struct || is_matrix(result_type))
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006855 SPIRV_CROSS_THROW("Cannot load array-of-array of composite type in tessellation IO.");
6856
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006857 expr += type_to_glsl(result_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006858 uint32_t num_control_points = to_array_size_literal(result_type, 1);
6859 uint32_t base_interface_index = interface_index;
6860
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006861 auto &sub_type = get<SPIRType>(result_type.parent_type);
6862
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006863 for (uint32_t i = 0; i < num_control_points; i++)
6864 {
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006865 expr += type_to_glsl(sub_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006866 interface_index = base_interface_index;
6867 uint32_t array_size = to_array_size_literal(result_type, 0);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006868 for (uint32_t j = 0; j < array_size; j++, interface_index++)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006869 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006870 const uint32_t indices[2] = { i, interface_index };
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006871
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006872 AccessChainMeta meta;
6873 expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
6874 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
6875 if (!is_matrix(sub_type) && sub_type.basetype != SPIRType::Struct &&
6876 expr_type.vecsize > sub_type.vecsize)
6877 expr += vector_swizzle(sub_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006878
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006879 if (j + 1 < array_size)
6880 expr += ", ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006881 }
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006882 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006883 if (i + 1 < num_control_points)
6884 expr += ", ";
6885 }
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006886 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006887 }
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006888 else if (result_type.basetype == SPIRType::Struct)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006889 {
6890 bool is_array_of_struct = is_array(result_type);
6891 if (is_array_of_struct && !ptr_is_io_variable)
6892 SPIRV_CROSS_THROW("Loading array of struct from IO variable must come directly from IO variable.");
6893
6894 uint32_t num_control_points = 1;
6895 if (is_array_of_struct)
6896 {
6897 num_control_points = to_array_size_literal(result_type, 0);
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006898 expr += type_to_glsl(result_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006899 }
6900
6901 auto &struct_type = is_array_of_struct ? get<SPIRType>(result_type.parent_type) : result_type;
6902 assert(struct_type.array.empty());
6903
6904 for (uint32_t i = 0; i < num_control_points; i++)
6905 {
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006906 expr += type_to_glsl(struct_type) + "{ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006907 for (uint32_t j = 0; j < uint32_t(struct_type.member_types.size()); j++)
6908 {
6909 // The base interface index is stored per variable for structs.
6910 if (var)
6911 {
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01006912 interface_index =
6913 get_extended_member_decoration(var->self, j, SPIRVCrossDecorationInterfaceMemberIndex);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006914 }
6915
6916 if (interface_index == uint32_t(-1))
6917 SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
6918
6919 const auto &mbr_type = get<SPIRType>(struct_type.member_types[j]);
Chip Davis688c5fc2020-02-20 21:38:28 -06006920 const auto &expr_mbr_type = get<SPIRType>(expr_type.member_types[j]);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006921 if (is_matrix(mbr_type) && ptr_type.storage == StorageClassInput)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006922 {
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006923 expr += type_to_glsl(mbr_type) + "(";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006924 for (uint32_t k = 0; k < mbr_type.columns; k++, interface_index++)
6925 {
6926 if (is_array_of_struct)
6927 {
6928 const uint32_t indices[2] = { i, interface_index };
6929 AccessChainMeta meta;
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01006930 expr += access_chain_internal(
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006931 stage_in_ptr_var_id, indices, 2,
6932 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006933 }
6934 else
6935 expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
Chip Davis688c5fc2020-02-20 21:38:28 -06006936 if (expr_mbr_type.vecsize > mbr_type.vecsize)
6937 expr += vector_swizzle(mbr_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006938
6939 if (k + 1 < mbr_type.columns)
6940 expr += ", ";
6941 }
6942 expr += ")";
6943 }
6944 else if (is_array(mbr_type))
6945 {
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006946 expr += type_to_glsl(mbr_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006947 uint32_t array_size = to_array_size_literal(mbr_type, 0);
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006948 for (uint32_t k = 0; k < array_size; k++, interface_index++)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006949 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006950 if (is_array_of_struct)
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006951 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006952 const uint32_t indices[2] = { i, interface_index };
6953 AccessChainMeta meta;
6954 expr += access_chain_internal(
6955 stage_in_ptr_var_id, indices, 2,
6956 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
Chip Davis688c5fc2020-02-20 21:38:28 -06006957 }
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006958 else
6959 expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
6960 if (expr_mbr_type.vecsize > mbr_type.vecsize)
6961 expr += vector_swizzle(mbr_type.vecsize, 0);
Chip Davis688c5fc2020-02-20 21:38:28 -06006962
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006963 if (k + 1 < array_size)
6964 expr += ", ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006965 }
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006966 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006967 }
6968 else
6969 {
6970 if (is_array_of_struct)
6971 {
6972 const uint32_t indices[2] = { i, interface_index };
6973 AccessChainMeta meta;
6974 expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01006975 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT,
6976 &meta);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006977 }
6978 else
6979 expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
Chip Davis688c5fc2020-02-20 21:38:28 -06006980 if (expr_mbr_type.vecsize > mbr_type.vecsize)
6981 expr += vector_swizzle(mbr_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006982 }
6983
6984 if (j + 1 < struct_type.member_types.size())
6985 expr += ", ";
6986 }
6987 expr += " }";
6988 if (i + 1 < num_control_points)
6989 expr += ", ";
6990 }
6991 if (is_array_of_struct)
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02006992 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006993 }
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02006994 else if (is_matrix(result_type))
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02006995 {
6996 bool is_array_of_matrix = is_array(result_type);
6997 if (is_array_of_matrix && !ptr_is_io_variable)
6998 SPIRV_CROSS_THROW("Loading array of matrix from IO variable must come directly from IO variable.");
6999 if (interface_index == uint32_t(-1))
7000 SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
7001
7002 if (is_array_of_matrix)
7003 {
7004 // Loading a matrix from each control point.
7005 uint32_t base_interface_index = interface_index;
7006 uint32_t num_control_points = to_array_size_literal(result_type, 0);
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007007 expr += type_to_glsl(result_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007008
7009 auto &matrix_type = get_variable_element_type(get<SPIRVariable>(ptr));
7010
7011 for (uint32_t i = 0; i < num_control_points; i++)
7012 {
7013 interface_index = base_interface_index;
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007014 expr += type_to_glsl(matrix_type) + "(";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007015 for (uint32_t j = 0; j < result_type.columns; j++, interface_index++)
7016 {
7017 const uint32_t indices[2] = { i, interface_index };
7018
7019 AccessChainMeta meta;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007020 expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
7021 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
Chip Davis688c5fc2020-02-20 21:38:28 -06007022 if (expr_type.vecsize > result_type.vecsize)
7023 expr += vector_swizzle(result_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007024 if (j + 1 < result_type.columns)
7025 expr += ", ";
7026 }
7027 expr += ")";
7028 if (i + 1 < num_control_points)
7029 expr += ", ";
7030 }
7031
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007032 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007033 }
7034 else
7035 {
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007036 expr += type_to_glsl(result_type) + "(";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007037 for (uint32_t i = 0; i < result_type.columns; i++, interface_index++)
7038 {
7039 expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
Chip Davis688c5fc2020-02-20 21:38:28 -06007040 if (expr_type.vecsize > result_type.vecsize)
7041 expr += vector_swizzle(result_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007042 if (i + 1 < result_type.columns)
7043 expr += ", ";
7044 }
7045 expr += ")";
7046 }
7047 }
7048 else if (ptr_is_io_variable)
7049 {
7050 assert(is_array(result_type));
7051 assert(result_type.array.size() == 1);
7052 if (interface_index == uint32_t(-1))
7053 SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
7054
7055 // We're loading an array directly from a global variable.
7056 // This means we're loading one member from each control point.
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007057 expr += type_to_glsl(result_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007058 uint32_t num_control_points = to_array_size_literal(result_type, 0);
7059
7060 for (uint32_t i = 0; i < num_control_points; i++)
7061 {
7062 const uint32_t indices[2] = { i, interface_index };
7063
7064 AccessChainMeta meta;
7065 expr += access_chain_internal(stage_in_ptr_var_id, indices, 2,
7066 ACCESS_CHAIN_INDEX_IS_LITERAL_BIT | ACCESS_CHAIN_PTR_CHAIN_BIT, &meta);
Chip Davis688c5fc2020-02-20 21:38:28 -06007067 if (expr_type.vecsize > result_type.vecsize)
7068 expr += vector_swizzle(result_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007069
7070 if (i + 1 < num_control_points)
7071 expr += ", ";
7072 }
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007073 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007074 }
7075 else
7076 {
7077 // We're loading an array from a concrete control point.
7078 assert(is_array(result_type));
7079 assert(result_type.array.size() == 1);
7080 if (interface_index == uint32_t(-1))
7081 SPIRV_CROSS_THROW("Interface index is unknown. Cannot continue.");
7082
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007083 expr += type_to_glsl(result_type) + "({ ";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007084 uint32_t array_size = to_array_size_literal(result_type, 0);
7085 for (uint32_t i = 0; i < array_size; i++, interface_index++)
7086 {
7087 expr += to_expression(ptr) + "." + to_member_name(iface_type, interface_index);
Chip Davis688c5fc2020-02-20 21:38:28 -06007088 if (expr_type.vecsize > result_type.vecsize)
7089 expr += vector_swizzle(result_type.vecsize, 0);
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007090 if (i + 1 < array_size)
7091 expr += ", ";
7092 }
Hans-Kristian Arntzenfa011f82019-10-26 17:57:34 +02007093 expr += " })";
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007094 }
7095
7096 emit_op(result_type_id, id, expr, false);
7097 register_read(id, ptr, false);
7098 return true;
7099}
7100
Chip Davise75add42019-02-05 18:13:26 -06007101bool CompilerMSL::emit_tessellation_access_chain(const uint32_t *ops, uint32_t length)
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007102{
7103 // If this is a per-vertex output, remap it to the I/O array buffer.
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007104
7105 // Any object which did not go through IO flattening shenanigans will go there instead.
7106 // We will unflatten on-demand instead as needed, but not all possible cases can be supported, especially with arrays.
7107
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007108 auto *var = maybe_get_backing_variable(ops[2]);
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007109 bool patch = false;
7110 bool flat_data = false;
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007111 bool ptr_is_chain = false;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007112 bool flatten_composites = false;
7113
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007114 bool is_block = false;
7115
7116 if (var)
7117 is_block = has_decoration(get_variable_data_type(*var).self, DecorationBlock);
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007118
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007119 if (var)
7120 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007121 flatten_composites = variable_storage_requires_stage_io(var->storage);
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01007122 patch = has_decoration(ops[2], DecorationPatch) || is_patch_block(get_variable_data_type(*var));
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007123
7124 // Should match strip_array in add_interface_block.
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01007125 flat_data = var->storage == StorageClassInput ||
7126 (var->storage == StorageClassOutput && get_execution_model() == ExecutionModelTessellationControl);
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007127
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007128 // Patch inputs are treated as normal block IO variables, so they don't deal with this path at all.
7129 if (patch && (!is_block || var->storage == StorageClassInput))
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007130 flat_data = false;
7131
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007132 // We might have a chained access chain, where
7133 // we first take the access chain to the control point, and then we chain into a member or something similar.
7134 // In this case, we need to skip gl_in/gl_out remapping.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007135 // Also, skip ptr chain for patches.
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007136 ptr_is_chain = var->self != ID(ops[2]);
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007137 }
7138
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007139 bool builtin_variable = false;
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007140 bool variable_is_flat = false;
7141
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007142 if (var && flat_data)
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007143 {
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007144 builtin_variable = is_builtin_variable(*var);
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007145
7146 BuiltIn bi_type = BuiltInMax;
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02007147 if (builtin_variable && !is_block)
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007148 bi_type = BuiltIn(get_decoration(var->self, DecorationBuiltIn));
7149
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02007150 variable_is_flat = !builtin_variable || is_block ||
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007151 bi_type == BuiltInPosition || bi_type == BuiltInPointSize ||
7152 bi_type == BuiltInClipDistance || bi_type == BuiltInCullDistance;
7153 }
7154
7155 if (variable_is_flat)
7156 {
7157 // If output is masked, it is emitted as a "normal" variable, just go through normal code paths.
7158 // Only check this for the first level of access chain.
7159 // Dealing with this for partial access chains should be possible, but awkward.
7160 if (var->storage == StorageClassOutput && !ptr_is_chain)
7161 {
7162 bool masked = false;
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02007163 if (is_block)
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007164 {
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007165 uint32_t relevant_member_index = patch ? 3 : 4;
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02007166 // FIXME: This won't work properly if the application first access chains into gl_out element,
7167 // then access chains into the member. Super weird, but theoretically possible ...
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007168 if (length > relevant_member_index)
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007169 {
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007170 uint32_t mbr_idx = get<SPIRConstant>(ops[relevant_member_index]).scalar();
Hans-Kristian Arntzenba93b652021-04-06 14:43:34 +02007171 masked = is_stage_output_block_member_masked(*var, mbr_idx, true);
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007172 }
7173 }
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +02007174 else if (var)
7175 masked = is_stage_output_variable_masked(*var);
Hans-Kristian Arntzenea915792021-03-26 16:16:03 +01007176
7177 if (masked)
7178 return false;
7179 }
7180
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007181 AccessChainMeta meta;
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02007182 SmallVector<uint32_t> indices;
Chip Davis884bc6d2020-07-22 15:25:10 -06007183 uint32_t next_id = ir.increase_bound_by(1);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007184
7185 indices.reserve(length - 3 + 1);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007186
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007187 uint32_t first_non_array_index = (ptr_is_chain ? 3 : 4) - (patch ? 1 : 0);
7188
7189 VariableID stage_var_id;
7190 if (patch)
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007191 stage_var_id = var->storage == StorageClassInput ? patch_stage_in_var_id : patch_stage_out_var_id;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007192 else
7193 stage_var_id = var->storage == StorageClassInput ? stage_in_ptr_var_id : stage_out_ptr_var_id;
7194
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007195 VariableID ptr = ptr_is_chain ? VariableID(ops[2]) : stage_var_id;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007196 if (!ptr_is_chain && !patch)
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007197 {
7198 // Index into gl_in/gl_out with first array index.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007199 indices.push_back(ops[first_non_array_index - 1]);
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007200 }
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007201
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007202 auto &result_ptr_type = get<SPIRType>(ops[0]);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007203
7204 uint32_t const_mbr_id = next_id++;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007205 uint32_t index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
7206
Hans-Kristian Arntzenbf3793d2021-05-21 16:32:03 +02007207 // If we have a pointer chain expression, and we are no longer pointing to a composite
7208 // object, we are in the clear. There is no longer a need to flatten anything.
7209 bool further_access_chain_is_trivial = false;
7210 if (ptr_is_chain && flatten_composites)
7211 {
7212 auto &ptr_type = expression_type(ptr);
7213 if (!is_array(ptr_type) && !is_matrix(ptr_type) && ptr_type.basetype != SPIRType::Struct)
7214 further_access_chain_is_trivial = true;
7215 }
7216
7217 if (!further_access_chain_is_trivial && (flatten_composites || is_block))
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007218 {
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007219 uint32_t i = first_non_array_index;
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007220 auto *type = &get_variable_element_type(*var);
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007221 if (index == uint32_t(-1) && length >= (first_non_array_index + 1))
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007222 {
7223 // Maybe this is a struct type in the input class, in which case
7224 // we put it as a decoration on the corresponding member.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007225 uint32_t mbr_idx = get_constant(ops[first_non_array_index]).scalar();
7226 index = get_extended_member_decoration(var->self, mbr_idx,
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007227 SPIRVCrossDecorationInterfaceMemberIndex);
7228 assert(index != uint32_t(-1));
7229 i++;
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007230 type = &get<SPIRType>(type->member_types[mbr_idx]);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007231 }
Hans-Kristian Arntzenbac2c342019-10-25 14:28:33 +02007232
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007233 // In this case, we're poking into flattened structures and arrays, so now we have to
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007234 // combine the following indices. If we encounter a non-constant index,
7235 // we're hosed.
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007236 for (; flatten_composites && i < length; ++i)
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007237 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007238 if (!is_array(*type) && !is_matrix(*type) && type->basetype != SPIRType::Struct)
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007239 break;
7240
Hans-Kristian Arntzen028ffc22019-10-25 10:53:12 +02007241 auto *c = maybe_get<SPIRConstant>(ops[i]);
7242 if (!c || c->specialization)
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01007243 SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable in tessellation. "
7244 "This is currently unsupported.");
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007245
7246 // We're in flattened space, so just increment the member index into IO block.
7247 // We can only do this once in the current implementation, so either:
7248 // Struct, Matrix or 1-dimensional array for a control point.
Hans-Kristian Arntzena59e25d2021-04-07 12:55:26 +02007249 if (type->basetype == SPIRType::Struct && var->storage == StorageClassOutput)
7250 {
7251 // Need to consider holes, since individual block members might be masked away.
7252 uint32_t mbr_idx = c->scalar();
7253 for (uint32_t j = 0; j < mbr_idx; j++)
7254 if (!is_stage_output_block_member_masked(*var, j, true))
7255 index++;
7256 }
7257 else
7258 index += c->scalar();
Hans-Kristian Arntzen028ffc22019-10-25 10:53:12 +02007259
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007260 if (type->parent_type)
7261 type = &get<SPIRType>(type->parent_type);
7262 else if (type->basetype == SPIRType::Struct)
Hans-Kristian Arntzen028ffc22019-10-25 10:53:12 +02007263 type = &get<SPIRType>(type->member_types[c->scalar()]);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007264 }
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007265
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007266 // We're not going to emit the actual member name, we let any further OpLoad take care of that.
7267 // Tag the access chain with the member index we're referencing.
7268 bool defer_access_chain = flatten_composites && (is_matrix(result_ptr_type) || is_array(result_ptr_type) ||
7269 result_ptr_type.basetype == SPIRType::Struct);
7270
7271 if (!defer_access_chain)
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007272 {
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007273 // Access the appropriate member of gl_in/gl_out.
Chip Davis884bc6d2020-07-22 15:25:10 -06007274 set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007275 indices.push_back(const_mbr_id);
7276
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007277 // Member index is now irrelevant.
7278 index = uint32_t(-1);
7279
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007280 // Append any straggling access chain indices.
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007281 if (i < length)
7282 indices.insert(indices.end(), ops + i, ops + length);
7283 }
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007284 else
7285 {
7286 // We must have consumed the entire access chain if we're deferring it.
7287 assert(i == length);
7288 }
7289
7290 if (index != uint32_t(-1))
7291 set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, index);
7292 else
7293 unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007294 }
7295 else
7296 {
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007297 if (index != uint32_t(-1))
7298 {
7299 set<SPIRConstant>(const_mbr_id, get_uint_type_id(), index, false);
7300 indices.push_back(const_mbr_id);
7301 }
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007302
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +02007303 // Member index is now irrelevant.
7304 index = uint32_t(-1);
7305 unset_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex);
7306
7307 indices.insert(indices.end(), ops + first_non_array_index, ops + length);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007308 }
7309
7310 // We use the pointer to the base of the input/output array here,
7311 // so this is always a pointer chain.
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007312 string e;
7313
7314 if (!ptr_is_chain)
7315 {
7316 // This is the start of an access chain, use ptr_chain to index into control point array.
Hans-Kristian Arntzen425e9682021-04-07 17:02:30 +02007317 e = access_chain(ptr, indices.data(), uint32_t(indices.size()), result_ptr_type, &meta, !patch);
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007318 }
7319 else
7320 {
7321 // If we're accessing a struct, we need to use member indices which are based on the IO block,
7322 // not actual struct type, so we have to use a split access chain here where
7323 // first path resolves the control point index, i.e. gl_in[index], and second half deals with
7324 // looking up flattened member name.
7325
7326 // However, it is possible that we partially accessed a struct,
7327 // by taking pointer to member inside the control-point array.
7328 // For this case, we fall back to a natural access chain since we have already dealt with remapping struct members.
7329 // One way to check this here is if we have 2 implied read expressions.
7330 // First one is the gl_in/gl_out struct itself, then an index into that array.
7331 // If we have traversed further, we use a normal access chain formulation.
7332 auto *ptr_expr = maybe_get<SPIRExpression>(ptr);
Hans-Kristian Arntzenbf3793d2021-05-21 16:32:03 +02007333 bool split_access_chain_formulation = flatten_composites && ptr_expr &&
7334 ptr_expr->implied_read_expressions.size() == 2 &&
7335 !further_access_chain_is_trivial;
7336
7337 if (split_access_chain_formulation)
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007338 {
7339 e = join(to_expression(ptr),
7340 access_chain_internal(stage_var_id, indices.data(), uint32_t(indices.size()),
7341 ACCESS_CHAIN_CHAIN_ONLY_BIT, &meta));
7342 }
7343 else
7344 {
7345 e = access_chain_internal(ptr, indices.data(), uint32_t(indices.size()), 0, &meta);
7346 }
7347 }
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007348
Chip Davis688c5fc2020-02-20 21:38:28 -06007349 // Get the actual type of the object that was accessed. If it's a vector type and we changed it,
7350 // then we'll need to add a swizzle.
7351 // For this, we can't necessarily rely on the type of the base expression, because it might be
7352 // another access chain, and it will therefore already have the "correct" type.
7353 auto *expr_type = &get_variable_data_type(*var);
7354 if (has_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID))
7355 expr_type = &get<SPIRType>(get_extended_decoration(ops[2], SPIRVCrossDecorationTessIOOriginalInputTypeID));
7356 for (uint32_t i = 3; i < length; i++)
7357 {
7358 if (!is_array(*expr_type) && expr_type->basetype == SPIRType::Struct)
7359 expr_type = &get<SPIRType>(expr_type->member_types[get<SPIRConstant>(ops[i]).scalar()]);
7360 else
7361 expr_type = &get<SPIRType>(expr_type->parent_type);
7362 }
7363 if (!is_array(*expr_type) && !is_matrix(*expr_type) && expr_type->basetype != SPIRType::Struct &&
7364 expr_type->vecsize > result_ptr_type.vecsize)
7365 e += vector_swizzle(result_ptr_type.vecsize, 0);
7366
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007367 auto &expr = set<SPIRExpression>(ops[1], move(e), ops[0], should_forward(ops[2]));
7368 expr.loaded_from = var->self;
7369 expr.need_transpose = meta.need_transpose;
7370 expr.access_chain = true;
7371
7372 // Mark the result as being packed if necessary.
7373 if (meta.storage_is_packed)
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +02007374 set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypePacked);
7375 if (meta.storage_physical_type != 0)
7376 set_extended_decoration(ops[1], SPIRVCrossDecorationPhysicalTypeID, meta.storage_physical_type);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007377 if (meta.storage_is_invariant)
7378 set_decoration(ops[1], DecorationInvariant);
Chip Davis688c5fc2020-02-20 21:38:28 -06007379 // Save the type we found in case the result is used in another access chain.
7380 set_extended_decoration(ops[1], SPIRVCrossDecorationTessIOOriginalInputTypeID, expr_type->self);
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007381
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007382 // If we have some expression dependencies in our access chain, this access chain is technically a forwarded
7383 // temporary which could be subject to invalidation.
7384 // Need to assume we're forwarded while calling inherit_expression_depdendencies.
7385 forwarded_temporaries.insert(ops[1]);
7386 // The access chain itself is never forced to a temporary, but its dependencies might.
7387 suppressed_usage_tracking.insert(ops[1]);
7388
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007389 for (uint32_t i = 2; i < length; i++)
7390 {
7391 inherit_expression_dependencies(ops[1], ops[i]);
7392 add_implied_read_expression(expr, ops[i]);
7393 }
7394
Hans-Kristian Arntzen27459592019-10-26 17:09:24 +02007395 // If we have no dependencies after all, i.e., all indices in the access chain are immutable temporaries,
7396 // we're not forwarded after all.
7397 if (expr.expression_dependencies.empty())
7398 forwarded_temporaries.erase(ops[1]);
7399
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007400 return true;
7401 }
7402
7403 // If this is the inner tessellation level, and we're tessellating triangles,
7404 // drop the last index. It isn't an array in this case, so we can't have an
7405 // array reference here. We need to make this ID a variable instead of an
7406 // expression so we don't try to dereference it as a variable pointer.
Chip Davis80954342019-02-20 00:33:46 -06007407 // Don't do this if the index is a constant 1, though. We need to drop stores
7408 // to that one.
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02007409 auto *m = ir.find_meta(var ? var->self : ID(0));
Chip Davise75add42019-02-05 18:13:26 -06007410 if (get_execution_model() == ExecutionModelTessellationControl && var && m &&
7411 m->decoration.builtin_type == BuiltInTessLevelInner && get_entry_point().flags.get(ExecutionModeTriangles))
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007412 {
Chip Davisba8593b2019-02-20 09:19:25 -06007413 auto *c = maybe_get<SPIRConstant>(ops[3]);
Hans-Kristian Arntzenc1a93b82019-02-20 17:27:15 +01007414 if (c && c->scalar() == 1)
7415 return false;
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01007416 auto &dest_var = set<SPIRVariable>(ops[1], *var);
7417 dest_var.basetype = ops[0];
7418 ir.meta[ops[1]] = ir.meta[ops[2]];
7419 inherit_expression_dependencies(ops[1], ops[2]);
7420 return true;
7421 }
7422
7423 return false;
7424}
7425
Chip Davisba8593b2019-02-20 09:19:25 -06007426bool CompilerMSL::is_out_of_bounds_tessellation_level(uint32_t id_lhs)
7427{
Chip Davis80954342019-02-20 00:33:46 -06007428 if (!get_entry_point().flags.get(ExecutionModeTriangles))
7429 return false;
7430
7431 // In SPIR-V, TessLevelInner always has two elements and TessLevelOuter always has
7432 // four. This is true even if we are tessellating triangles. This allows clients
7433 // to use a single tessellation control shader with multiple tessellation evaluation
7434 // shaders.
7435 // In Metal, however, only the first element of TessLevelInner and the first three
7436 // of TessLevelOuter are accessible. This stems from how in Metal, the tessellation
7437 // levels must be stored to a dedicated buffer in a particular format that depends
7438 // on the patch type. Therefore, in Triangles mode, any access to the second
7439 // inner level or the fourth outer level must be dropped.
7440 const auto *e = maybe_get<SPIRExpression>(id_lhs);
Hans-Kristian Arntzenc1a93b82019-02-20 17:27:15 +01007441 if (!e || !e->access_chain)
7442 return false;
Chip Davis80954342019-02-20 00:33:46 -06007443 BuiltIn builtin = BuiltIn(get_decoration(e->loaded_from, DecorationBuiltIn));
Hans-Kristian Arntzenc1a93b82019-02-20 17:27:15 +01007444 if (builtin != BuiltInTessLevelInner && builtin != BuiltInTessLevelOuter)
7445 return false;
Chip Davis80954342019-02-20 00:33:46 -06007446 auto *c = maybe_get<SPIRConstant>(e->implied_read_expressions[1]);
Hans-Kristian Arntzenc1a93b82019-02-20 17:27:15 +01007447 if (!c)
7448 return false;
7449 return (builtin == BuiltInTessLevelInner && c->scalar() == 1) ||
7450 (builtin == BuiltInTessLevelOuter && c->scalar() == 3);
Chip Davis80954342019-02-20 00:33:46 -06007451}
7452
Hans-Kristian Arntzenfa5b2062020-07-01 13:02:11 +02007453void CompilerMSL::prepare_access_chain_for_scalar_access(std::string &expr, const SPIRType &type,
7454 spv::StorageClass storage, bool &is_packed)
7455{
7456 // If there is any risk of writes happening with the access chain in question,
7457 // and there is a risk of concurrent write access to other components,
7458 // we must cast the access chain to a plain pointer to ensure we only access the exact scalars we expect.
7459 // The MSL compiler refuses to allow component-level access for any non-packed vector types.
7460 if (!is_packed && (storage == StorageClassStorageBuffer || storage == StorageClassWorkgroup))
7461 {
7462 const char *addr_space = storage == StorageClassWorkgroup ? "threadgroup" : "device";
7463 expr = join("((", addr_space, " ", type_to_glsl(type), "*)&", enclose_expression(expr), ")");
7464
7465 // Further indexing should happen with packed rules (array index, not swizzle).
7466 is_packed = true;
7467 }
7468}
7469
Hans-Kristian Arntzen75ed7382021-04-14 15:10:02 +02007470bool CompilerMSL::access_chain_needs_stage_io_builtin_translation(uint32_t base)
7471{
7472 auto *var = maybe_get_backing_variable(base);
7473 if (!var || !is_tessellation_shader())
7474 return true;
7475
7476 // We only need to rewrite builtin access chains when accessing flattened builtins like gl_ClipDistance_N.
7477 // Avoid overriding it back to just gl_ClipDistance.
7478 // This can only happen in scenarios where we cannot flatten/unflatten access chains, so, the only case
7479 // where this triggers is evaluation shader inputs.
7480 bool redirect_builtin = get_execution_model() == ExecutionModelTessellationEvaluation ?
7481 var->storage == StorageClassOutput : false;
7482 return redirect_builtin;
7483}
7484
Chip Davisaca9b682020-11-02 20:56:46 -06007485// Sets the interface member index for an access chain to a pull-model interpolant.
7486void CompilerMSL::fix_up_interpolant_access_chain(const uint32_t *ops, uint32_t length)
7487{
7488 auto *var = maybe_get_backing_variable(ops[2]);
7489 if (!var || !pull_model_inputs.count(var->self))
7490 return;
7491 // Get the base index.
7492 uint32_t interface_index;
7493 auto &var_type = get_variable_data_type(*var);
7494 auto &result_type = get<SPIRType>(ops[0]);
7495 auto *type = &var_type;
7496 if (has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex))
7497 {
7498 interface_index = get_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex);
7499 }
7500 else
7501 {
7502 // Assume an access chain into a struct variable.
7503 assert(var_type.basetype == SPIRType::Struct);
7504 auto &c = get<SPIRConstant>(ops[3 + var_type.array.size()]);
Hans-Kristian Arntzen6fc2a052020-11-08 13:59:52 +01007505 interface_index =
7506 get_extended_member_decoration(var->self, c.scalar(), SPIRVCrossDecorationInterfaceMemberIndex);
Chip Davisaca9b682020-11-02 20:56:46 -06007507 }
7508 // Accumulate indices. We'll have to skip over the one for the struct, if present, because we already accounted
7509 // for that getting the base index.
7510 for (uint32_t i = 3; i < length; ++i)
7511 {
Bill Hollings3e04eee2021-07-12 14:52:07 -04007512 if (is_vector(*type) && !is_array(*type) && is_scalar(result_type))
Chip Davisaca9b682020-11-02 20:56:46 -06007513 {
7514 // We don't want to combine the next index. Actually, we need to save it
7515 // so we know to apply a swizzle to the result of the interpolation.
7516 set_extended_decoration(ops[1], SPIRVCrossDecorationInterpolantComponentExpr, ops[i]);
7517 break;
7518 }
7519
7520 auto *c = maybe_get<SPIRConstant>(ops[i]);
7521 if (!c || c->specialization)
7522 SPIRV_CROSS_THROW("Trying to dynamically index into an array interface variable using pull-model "
7523 "interpolation. This is currently unsupported.");
7524
7525 if (type->parent_type)
7526 type = &get<SPIRType>(type->parent_type);
7527 else if (type->basetype == SPIRType::Struct)
7528 type = &get<SPIRType>(type->member_types[c->scalar()]);
7529
7530 if (!has_extended_decoration(ops[2], SPIRVCrossDecorationInterfaceMemberIndex) &&
7531 i - 3 == var_type.array.size())
7532 continue;
7533
7534 interface_index += c->scalar();
7535 }
7536 // Save this to the access chain itself so we can recover it later when calling an interpolation function.
7537 set_extended_decoration(ops[1], SPIRVCrossDecorationInterfaceMemberIndex, interface_index);
7538}
7539
Bill Hollingsf5f91042016-10-27 18:47:17 -04007540// Override for MSL-specific syntax instructions
7541void CompilerMSL::emit_instruction(const Instruction &instruction)
7542{
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007543#define MSL_BOP(op) emit_binary_op(ops[0], ops[1], ops[2], ops[3], #op)
7544#define MSL_BOP_CAST(op, type) \
Hans-Kristian Arntzen67aad482016-11-12 10:04:50 +01007545 emit_binary_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode))
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007546#define MSL_UOP(op) emit_unary_op(ops[0], ops[1], ops[2], #op)
7547#define MSL_QFOP(op) emit_quaternary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], #op)
7548#define MSL_TFOP(op) emit_trinary_func_op(ops[0], ops[1], ops[2], ops[3], ops[4], #op)
7549#define MSL_BFOP(op) emit_binary_func_op(ops[0], ops[1], ops[2], ops[3], #op)
7550#define MSL_BFOP_CAST(op, type) \
Hans-Kristian Arntzen67aad482016-11-12 10:04:50 +01007551 emit_binary_func_op_cast(ops[0], ops[1], ops[2], ops[3], #op, type, opcode_is_sign_invariant(opcode))
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007552#define MSL_UFOP(op) emit_unary_func_op(ops[0], ops[1], ops[2], #op)
Chip Davisd3233692018-08-31 13:46:02 -05007553#define MSL_UNORD_BOP(op) emit_binary_unord_op(ops[0], ops[1], ops[2], ops[3], #op)
Bill Hollingsf5f91042016-10-27 18:47:17 -04007554
7555 auto ops = stream(instruction);
7556 auto opcode = static_cast<Op>(instruction.op);
7557
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007558 // If we need to do implicit bitcasts, make sure we do it with the correct type.
7559 uint32_t integer_width = get_integer_width_for_instruction(instruction);
7560 auto int_type = to_signed_basetype(integer_width);
7561 auto uint_type = to_unsigned_basetype(integer_width);
7562
Bill Hollingsf5f91042016-10-27 18:47:17 -04007563 switch (opcode)
7564 {
Mark Satterthwaite40a44562019-08-14 10:54:18 -04007565 case OpLoad:
7566 {
7567 uint32_t id = ops[1];
7568 uint32_t ptr = ops[2];
Hans-Kristian Arntzen27d6d452019-10-25 16:41:02 +02007569 if (is_tessellation_shader())
7570 {
7571 if (!emit_tessellation_io_load(ops[0], id, ptr))
7572 CompilerGLSL::emit_instruction(instruction);
7573 }
7574 else
7575 {
7576 // Sample mask input for Metal is not an array
7577 if (BuiltIn(get_decoration(ptr, DecorationBuiltIn)) == BuiltInSampleMask)
7578 set_decoration(id, DecorationBuiltIn, BuiltInSampleMask);
7579 CompilerGLSL::emit_instruction(instruction);
7580 }
Mark Satterthwaite40a44562019-08-14 10:54:18 -04007581 break;
7582 }
Bill Hollingsaca1b552016-12-04 12:32:58 -05007583
Bill Hollingsf5f91042016-10-27 18:47:17 -04007584 // Comparisons
7585 case OpIEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007586 MSL_BOP_CAST(==, int_type);
7587 break;
7588
Bill Hollingsf5f91042016-10-27 18:47:17 -04007589 case OpLogicalEqual:
7590 case OpFOrdEqual:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007591 MSL_BOP(==);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007592 break;
7593
7594 case OpINotEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007595 MSL_BOP_CAST(!=, int_type);
7596 break;
7597
Bill Hollingsf5f91042016-10-27 18:47:17 -04007598 case OpLogicalNotEqual:
7599 case OpFOrdNotEqual:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007600 MSL_BOP(!=);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007601 break;
7602
7603 case OpUGreaterThan:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007604 MSL_BOP_CAST(>, uint_type);
7605 break;
7606
Bill Hollingsf5f91042016-10-27 18:47:17 -04007607 case OpSGreaterThan:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007608 MSL_BOP_CAST(>, int_type);
7609 break;
7610
Bill Hollingsf5f91042016-10-27 18:47:17 -04007611 case OpFOrdGreaterThan:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007612 MSL_BOP(>);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007613 break;
7614
7615 case OpUGreaterThanEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007616 MSL_BOP_CAST(>=, uint_type);
7617 break;
7618
Bill Hollingsf5f91042016-10-27 18:47:17 -04007619 case OpSGreaterThanEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007620 MSL_BOP_CAST(>=, int_type);
7621 break;
7622
Bill Hollingsf5f91042016-10-27 18:47:17 -04007623 case OpFOrdGreaterThanEqual:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007624 MSL_BOP(>=);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007625 break;
7626
7627 case OpULessThan:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007628 MSL_BOP_CAST(<, uint_type);
7629 break;
7630
Bill Hollingsf5f91042016-10-27 18:47:17 -04007631 case OpSLessThan:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007632 MSL_BOP_CAST(<, int_type);
7633 break;
7634
Bill Hollingsf5f91042016-10-27 18:47:17 -04007635 case OpFOrdLessThan:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007636 MSL_BOP(<);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007637 break;
7638
7639 case OpULessThanEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007640 MSL_BOP_CAST(<=, uint_type);
7641 break;
7642
Bill Hollingsf5f91042016-10-27 18:47:17 -04007643 case OpSLessThanEqual:
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +01007644 MSL_BOP_CAST(<=, int_type);
7645 break;
7646
Bill Hollingsf5f91042016-10-27 18:47:17 -04007647 case OpFOrdLessThanEqual:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007648 MSL_BOP(<=);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007649 break;
7650
Chip Davisd3233692018-08-31 13:46:02 -05007651 case OpFUnordEqual:
7652 MSL_UNORD_BOP(==);
7653 break;
7654
7655 case OpFUnordNotEqual:
7656 MSL_UNORD_BOP(!=);
7657 break;
7658
7659 case OpFUnordGreaterThan:
7660 MSL_UNORD_BOP(>);
7661 break;
7662
7663 case OpFUnordGreaterThanEqual:
7664 MSL_UNORD_BOP(>=);
7665 break;
7666
7667 case OpFUnordLessThan:
7668 MSL_UNORD_BOP(<);
7669 break;
7670
7671 case OpFUnordLessThanEqual:
7672 MSL_UNORD_BOP(<=);
7673 break;
7674
Bill Hollingsf5f91042016-10-27 18:47:17 -04007675 // Derivatives
7676 case OpDPdx:
Bill Hollings8f6df772017-05-19 18:14:08 -04007677 case OpDPdxFine:
7678 case OpDPdxCoarse:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007679 MSL_UFOP(dfdx);
Hans-Kristian Arntzen938c7de2018-03-12 17:34:54 +01007680 register_control_dependent_expression(ops[1]);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007681 break;
7682
7683 case OpDPdy:
Bill Hollings8f6df772017-05-19 18:14:08 -04007684 case OpDPdyFine:
7685 case OpDPdyCoarse:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007686 MSL_UFOP(dfdy);
Hans-Kristian Arntzen938c7de2018-03-12 17:34:54 +01007687 register_control_dependent_expression(ops[1]);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007688 break;
7689
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +01007690 case OpFwidth:
7691 case OpFwidthCoarse:
7692 case OpFwidthFine:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007693 MSL_UFOP(fwidth);
Hans-Kristian Arntzen938c7de2018-03-12 17:34:54 +01007694 register_control_dependent_expression(ops[1]);
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +01007695 break;
7696
Bill Hollings8f6df772017-05-19 18:14:08 -04007697 // Bitfield
7698 case OpBitFieldInsert:
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007699 {
Hans-Kristian Arntzen3ccfbce2019-08-28 14:25:26 +02007700 emit_bitfield_insert_op(ops[0], ops[1], ops[2], ops[3], ops[4], ops[5], "insert_bits", SPIRType::UInt);
Bill Hollings8f6df772017-05-19 18:14:08 -04007701 break;
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007702 }
Bill Hollings8f6df772017-05-19 18:14:08 -04007703
7704 case OpBitFieldSExtract:
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007705 {
Hans-Kristian Arntzen3ccfbce2019-08-28 14:25:26 +02007706 emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", int_type, int_type,
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007707 SPIRType::UInt, SPIRType::UInt);
Bill Hollings8f6df772017-05-19 18:14:08 -04007708 break;
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007709 }
7710
7711 case OpBitFieldUExtract:
7712 {
Hans-Kristian Arntzen3ccfbce2019-08-28 14:25:26 +02007713 emit_trinary_func_op_bitextract(ops[0], ops[1], ops[2], ops[3], ops[4], "extract_bits", uint_type, uint_type,
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007714 SPIRType::UInt, SPIRType::UInt);
7715 break;
7716 }
Bill Hollings8f6df772017-05-19 18:14:08 -04007717
7718 case OpBitReverse:
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007719 // BitReverse does not have issues with sign since result type must match input type.
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007720 MSL_UFOP(reverse_bits);
Bill Hollings8f6df772017-05-19 18:14:08 -04007721 break;
7722
7723 case OpBitCount:
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007724 {
7725 auto basetype = expression_type(ops[2]).basetype;
7726 emit_unary_func_op_cast(ops[0], ops[1], ops[2], "popcount", basetype, basetype);
Bill Hollings8f6df772017-05-19 18:14:08 -04007727 break;
Hans-Kristian Arntzenb3305792019-08-26 11:01:14 +02007728 }
Bill Hollings8f6df772017-05-19 18:14:08 -04007729
Hans-Kristian Arntzen3fa6cc82018-02-15 13:31:29 +01007730 case OpFRem:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007731 MSL_BFOP(fmod);
Hans-Kristian Arntzen3fa6cc82018-02-15 13:31:29 +01007732 break;
7733
Mark Satterthwaite69b703f2019-08-14 11:25:18 -04007734 case OpFMul:
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02007735 if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction))
Lukas Hermanns51be6012019-09-17 15:10:39 -04007736 MSL_BFOP(spvFMul);
Mark Satterthwaite69b703f2019-08-14 11:25:18 -04007737 else
7738 MSL_BOP(*);
7739 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04007740
Mark Satterthwaite69b703f2019-08-14 11:25:18 -04007741 case OpFAdd:
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02007742 if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction))
Lukas Hermanns51be6012019-09-17 15:10:39 -04007743 MSL_BFOP(spvFAdd);
Mark Satterthwaite69b703f2019-08-14 11:25:18 -04007744 else
7745 MSL_BOP(+);
7746 break;
Bill Hollingsf5f91042016-10-27 18:47:17 -04007747
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02007748 case OpFSub:
7749 if (msl_options.invariant_float_math || has_decoration(ops[1], DecorationNoContraction))
7750 MSL_BFOP(spvFSub);
7751 else
7752 MSL_BOP(-);
7753 break;
7754
Bill Hollingsf5f91042016-10-27 18:47:17 -04007755 // Atomics
7756 case OpAtomicExchange:
7757 {
7758 uint32_t result_type = ops[0];
7759 uint32_t id = ops[1];
Bill Hollings8f6df772017-05-19 18:14:08 -04007760 uint32_t ptr = ops[2];
7761 uint32_t mem_sem = ops[4];
7762 uint32_t val = ops[5];
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01007763 emit_atomic_func_op(result_type, id, "atomic_exchange_explicit", opcode, mem_sem, mem_sem, false, ptr, val);
Bill Hollingsf5f91042016-10-27 18:47:17 -04007764 break;
7765 }
7766
Bill Hollings8f6df772017-05-19 18:14:08 -04007767 case OpAtomicCompareExchange:
Bill Hollings8f6df772017-05-19 18:14:08 -04007768 {
7769 uint32_t result_type = ops[0];
7770 uint32_t id = ops[1];
7771 uint32_t ptr = ops[2];
7772 uint32_t mem_sem_pass = ops[4];
7773 uint32_t mem_sem_fail = ops[5];
7774 uint32_t val = ops[6];
7775 uint32_t comp = ops[7];
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01007776 emit_atomic_func_op(result_type, id, "atomic_compare_exchange_weak_explicit", opcode,
7777 mem_sem_pass, mem_sem_fail, true,
Chip Davis41eb5c42018-09-10 14:47:35 -05007778 ptr, comp, true, false, val);
Bill Hollings8f6df772017-05-19 18:14:08 -04007779 break;
7780 }
7781
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02007782 case OpAtomicCompareExchangeWeak:
7783 SPIRV_CROSS_THROW("OpAtomicCompareExchangeWeak is only supported in kernel profile.");
7784
Bill Hollings8f6df772017-05-19 18:14:08 -04007785 case OpAtomicLoad:
7786 {
7787 uint32_t result_type = ops[0];
7788 uint32_t id = ops[1];
7789 uint32_t ptr = ops[2];
7790 uint32_t mem_sem = ops[4];
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01007791 emit_atomic_func_op(result_type, id, "atomic_load_explicit", opcode, mem_sem, mem_sem, false, ptr, 0);
Bill Hollings8f6df772017-05-19 18:14:08 -04007792 break;
7793 }
7794
7795 case OpAtomicStore:
7796 {
7797 uint32_t result_type = expression_type(ops[0]).self;
7798 uint32_t id = ops[0];
7799 uint32_t ptr = ops[0];
7800 uint32_t mem_sem = ops[2];
7801 uint32_t val = ops[3];
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01007802 emit_atomic_func_op(result_type, id, "atomic_store_explicit", opcode, mem_sem, mem_sem, false, ptr, val);
Bill Hollings8f6df772017-05-19 18:14:08 -04007803 break;
7804 }
7805
Chip Davis41eb5c42018-09-10 14:47:35 -05007806#define MSL_AFMO_IMPL(op, valsrc, valconst) \
7807 do \
7808 { \
7809 uint32_t result_type = ops[0]; \
7810 uint32_t id = ops[1]; \
7811 uint32_t ptr = ops[2]; \
7812 uint32_t mem_sem = ops[4]; \
7813 uint32_t val = valsrc; \
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01007814 emit_atomic_func_op(result_type, id, "atomic_fetch_" #op "_explicit", opcode, \
7815 mem_sem, mem_sem, false, ptr, val, \
Chip Davis41eb5c42018-09-10 14:47:35 -05007816 false, valconst); \
Bill Hollings542e8c32017-05-22 13:38:23 -04007817 } while (false)
Bill Hollings8f6df772017-05-19 18:14:08 -04007818
Chip Davis41eb5c42018-09-10 14:47:35 -05007819#define MSL_AFMO(op) MSL_AFMO_IMPL(op, ops[5], false)
7820#define MSL_AFMIO(op) MSL_AFMO_IMPL(op, 1, true)
Bill Hollings8f6df772017-05-19 18:14:08 -04007821
7822 case OpAtomicIIncrement:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007823 MSL_AFMIO(add);
Bill Hollings542e8c32017-05-22 13:38:23 -04007824 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007825
7826 case OpAtomicIDecrement:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007827 MSL_AFMIO(sub);
Bill Hollings542e8c32017-05-22 13:38:23 -04007828 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007829
7830 case OpAtomicIAdd:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007831 MSL_AFMO(add);
Bill Hollings542e8c32017-05-22 13:38:23 -04007832 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007833
7834 case OpAtomicISub:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007835 MSL_AFMO(sub);
Bill Hollings542e8c32017-05-22 13:38:23 -04007836 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007837
7838 case OpAtomicSMin:
7839 case OpAtomicUMin:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007840 MSL_AFMO(min);
Bill Hollings542e8c32017-05-22 13:38:23 -04007841 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007842
7843 case OpAtomicSMax:
7844 case OpAtomicUMax:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007845 MSL_AFMO(max);
Bill Hollings542e8c32017-05-22 13:38:23 -04007846 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007847
7848 case OpAtomicAnd:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007849 MSL_AFMO(and);
Bill Hollings542e8c32017-05-22 13:38:23 -04007850 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007851
7852 case OpAtomicOr:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02007853 MSL_AFMO(or);
Bill Hollings542e8c32017-05-22 13:38:23 -04007854 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007855
7856 case OpAtomicXor:
Bill Hollingsac238b82018-07-26 00:50:33 -04007857 MSL_AFMO(xor);
Bill Hollings542e8c32017-05-22 13:38:23 -04007858 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04007859
7860 // Images
7861
Bill Hollings6f3381a2017-06-01 16:29:39 -04007862 // Reads == Fetches in Metal
Bill Hollings8f6df772017-05-19 18:14:08 -04007863 case OpImageRead:
Bill Hollings6f3381a2017-06-01 16:29:39 -04007864 {
7865 // Mark that this shader reads from this image
7866 uint32_t img_id = ops[2];
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01007867 auto &type = expression_type(img_id);
7868 if (type.image.dim != DimSubpassData)
Vadim Shcherbakov6c41f9e2017-12-06 09:51:23 -08007869 {
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01007870 auto *p_var = maybe_get_backing_variable(img_id);
7871 if (p_var && has_decoration(p_var->self, DecorationNonReadable))
7872 {
7873 unset_decoration(p_var->self, DecorationNonReadable);
Hans-Kristian Arntzen317144a2019-04-05 12:06:10 +02007874 force_recompile();
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01007875 }
Vadim Shcherbakov6c41f9e2017-12-06 09:51:23 -08007876 }
Bill Hollings6f3381a2017-06-01 16:29:39 -04007877
Hans-Kristian Arntzen275974e2020-06-04 15:50:28 +02007878 emit_texture_op(instruction, false);
Bill Hollings8f6df772017-05-19 18:14:08 -04007879 break;
Bill Hollings6f3381a2017-06-01 16:29:39 -04007880 }
Bill Hollings8f6df772017-05-19 18:14:08 -04007881
Lukas Hermanns50ac6862019-09-18 14:03:54 -04007882 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007883 case OpImageTexelPointer:
7884 {
7885 // When using the pointer, we need to know which variable it is actually loaded from.
7886 auto *var = maybe_get_backing_variable(ops[2]);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +02007887 if (var && atomic_image_vars.count(var->self))
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007888 {
7889 uint32_t result_type = ops[0];
7890 uint32_t id = ops[1];
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04007891
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007892 std::string coord = to_expression(ops[3]);
7893 auto &type = expression_type(ops[2]);
7894 if (type.image.dim == Dim2D)
7895 {
7896 coord = join("spvImage2DAtomicCoord(", coord, ", ", to_expression(ops[2]), ")");
7897 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04007898
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007899 auto &e = set<SPIRExpression>(id, join(to_expression(ops[2]), "_atomic[", coord, "]"), result_type, true);
Lukas Hermanns37df7402019-09-20 09:28:46 -04007900 e.loaded_from = var ? var->self : ID(0);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +02007901 inherit_expression_dependencies(id, ops[3]);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007902 }
7903 else
7904 {
Mark Satterthwaitec4f97042019-08-26 11:28:13 -04007905 uint32_t result_type = ops[0];
7906 uint32_t id = ops[1];
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04007907 auto &e =
7908 set<SPIRExpression>(id, join(to_expression(ops[2]), ", ", to_expression(ops[3])), result_type, true);
Mark Satterthwaitec4f97042019-08-26 11:28:13 -04007909
7910 // When using the pointer, we need to know which variable it is actually loaded from.
Lukas Hermanns37df7402019-09-20 09:28:46 -04007911 e.loaded_from = var ? var->self : ID(0);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +02007912 inherit_expression_dependencies(id, ops[3]);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007913 }
7914 break;
7915 }
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04007916
Bill Hollings8f6df772017-05-19 18:14:08 -04007917 case OpImageWrite:
7918 {
7919 uint32_t img_id = ops[0];
7920 uint32_t coord_id = ops[1];
7921 uint32_t texel_id = ops[2];
7922 const uint32_t *opt = &ops[3];
Chip Davis680ef9d2018-09-04 01:15:17 -05007923 uint32_t length = instruction.length - 3;
Bill Hollings8f6df772017-05-19 18:14:08 -04007924
7925 // Bypass pointers because we need the real image struct
7926 auto &type = expression_type(img_id);
7927 auto &img_type = get<SPIRType>(type.self);
7928
7929 // Ensure this image has been marked as being written to and force a
7930 // recommpile so that the image type output will include write access
Bill Hollingsb41e1482017-05-29 20:45:05 -04007931 auto *p_var = maybe_get_backing_variable(img_id);
7932 if (p_var && has_decoration(p_var->self, DecorationNonWritable))
Bill Hollings8f6df772017-05-19 18:14:08 -04007933 {
Bill Hollingsb41e1482017-05-29 20:45:05 -04007934 unset_decoration(p_var->self, DecorationNonWritable);
Hans-Kristian Arntzen317144a2019-04-05 12:06:10 +02007935 force_recompile();
Bill Hollings8f6df772017-05-19 18:14:08 -04007936 }
7937
Bill Hollings8f6df772017-05-19 18:14:08 -04007938 bool forward = false;
7939 uint32_t bias = 0;
7940 uint32_t lod = 0;
7941 uint32_t flags = 0;
7942
7943 if (length)
7944 {
7945 flags = *opt++;
7946 length--;
7947 }
7948
7949 auto test = [&](uint32_t &v, uint32_t flag) {
7950 if (length && (flags & flag))
7951 {
7952 v = *opt++;
7953 length--;
7954 }
7955 };
7956
7957 test(bias, ImageOperandsBiasMask);
7958 test(lod, ImageOperandsLodMask);
7959
Hans-Kristian Arntzen3aa08f72019-01-17 14:53:42 +01007960 auto &texel_type = expression_type(texel_id);
7961 auto store_type = texel_type;
7962 store_type.vecsize = 4;
7963
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02007964 TextureFunctionArguments args = {};
7965 args.base.img = img_id;
7966 args.base.imgtype = &img_type;
7967 args.base.is_fetch = true;
7968 args.coord = coord_id;
7969 args.lod = lod;
Hans-Kristian Arntzenb4e01632019-06-21 16:02:22 +02007970 statement(join(to_expression(img_id), ".write(",
7971 remap_swizzle(store_type, texel_type.vecsize, to_expression(texel_id)), ", ",
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02007972 CompilerMSL::to_function_args(args, &forward), ");"));
Bill Hollings8f6df772017-05-19 18:14:08 -04007973
Bill Hollingsb41e1482017-05-29 20:45:05 -04007974 if (p_var && variable_storage_is_aliased(*p_var))
Bill Hollings8f6df772017-05-19 18:14:08 -04007975 flush_all_aliased_variables();
7976
7977 break;
7978 }
7979
7980 case OpImageQuerySize:
7981 case OpImageQuerySizeLod:
7982 {
7983 uint32_t rslt_type_id = ops[0];
7984 auto &rslt_type = get<SPIRType>(rslt_type_id);
7985
7986 uint32_t id = ops[1];
7987
7988 uint32_t img_id = ops[2];
7989 string img_exp = to_expression(img_id);
7990 auto &img_type = expression_type(img_id);
7991 Dim img_dim = img_type.image.dim;
Hans-Kristian Arntzenca69b612017-11-06 09:49:52 +01007992 bool img_is_array = img_type.image.arrayed;
Bill Hollings8f6df772017-05-19 18:14:08 -04007993
7994 if (img_type.basetype != SPIRType::Image)
7995 SPIRV_CROSS_THROW("Invalid type for OpImageQuerySize.");
7996
7997 string lod;
7998 if (opcode == OpImageQuerySizeLod)
7999 {
8000 // LOD index defaults to zero, so don't bother outputing level zero index
8001 string decl_lod = to_expression(ops[3]);
8002 if (decl_lod != "0")
8003 lod = decl_lod;
8004 }
8005
8006 string expr = type_to_glsl(rslt_type) + "(";
8007 expr += img_exp + ".get_width(" + lod + ")";
8008
8009 if (img_dim == Dim2D || img_dim == DimCube || img_dim == Dim3D)
8010 expr += ", " + img_exp + ".get_height(" + lod + ")";
8011
8012 if (img_dim == Dim3D)
8013 expr += ", " + img_exp + ".get_depth(" + lod + ")";
8014
Hans-Kristian Arntzenca69b612017-11-06 09:49:52 +01008015 if (img_is_array)
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04008016 {
Bill Hollings8f6df772017-05-19 18:14:08 -04008017 expr += ", " + img_exp + ".get_array_size()";
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04008018 if (img_dim == DimCube && msl_options.emulate_cube_array)
8019 expr += " / 6";
8020 }
Bill Hollings8f6df772017-05-19 18:14:08 -04008021
8022 expr += ")";
8023
8024 emit_op(rslt_type_id, id, expr, should_forward(img_id));
8025
8026 break;
8027 }
8028
Hans-Kristian Arntzen71bb7782018-09-13 13:44:46 +02008029 case OpImageQueryLod:
Hans-Kristian Arntzen0671b3c2019-06-12 11:36:52 +02008030 {
8031 if (!msl_options.supports_msl_version(2, 2))
8032 SPIRV_CROSS_THROW("ImageQueryLod is only supported on MSL 2.2 and up.");
8033 uint32_t result_type = ops[0];
8034 uint32_t id = ops[1];
8035 uint32_t image_id = ops[2];
8036 uint32_t coord_id = ops[3];
8037 emit_uninitialized_temporary_expression(result_type, id);
8038
8039 auto sampler_expr = to_sampler_expression(image_id);
8040 auto *combined = maybe_get<SPIRCombinedImageSampler>(image_id);
8041 auto image_expr = combined ? to_expression(combined->image) : to_expression(image_id);
8042
8043 // TODO: It is unclear if calculcate_clamped_lod also conditionally rounds
8044 // the reported LOD based on the sampler. NEAREST miplevel should
8045 // round the LOD, but LINEAR miplevel should not round.
8046 // Let's hope this does not become an issue ...
Hans-Kristian Arntzenb4e01632019-06-21 16:02:22 +02008047 statement(to_expression(id), ".x = ", image_expr, ".calculate_clamped_lod(", sampler_expr, ", ",
8048 to_expression(coord_id), ");");
8049 statement(to_expression(id), ".y = ", image_expr, ".calculate_unclamped_lod(", sampler_expr, ", ",
8050 to_expression(coord_id), ");");
Hans-Kristian Arntzen0671b3c2019-06-12 11:36:52 +02008051 register_control_dependent_expression(id);
8052 break;
8053 }
Hans-Kristian Arntzen71bb7782018-09-13 13:44:46 +02008054
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02008055#define MSL_ImgQry(qrytype) \
Bill Hollings542e8c32017-05-22 13:38:23 -04008056 do \
Bill Hollings8f6df772017-05-19 18:14:08 -04008057 { \
8058 uint32_t rslt_type_id = ops[0]; \
8059 auto &rslt_type = get<SPIRType>(rslt_type_id); \
8060 uint32_t id = ops[1]; \
8061 uint32_t img_id = ops[2]; \
8062 string img_exp = to_expression(img_id); \
8063 string expr = type_to_glsl(rslt_type) + "(" + img_exp + ".get_num_" #qrytype "())"; \
8064 emit_op(rslt_type_id, id, expr, should_forward(img_id)); \
Bill Hollings542e8c32017-05-22 13:38:23 -04008065 } while (false)
Bill Hollings8f6df772017-05-19 18:14:08 -04008066
8067 case OpImageQueryLevels:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02008068 MSL_ImgQry(mip_levels);
Bill Hollings542e8c32017-05-22 13:38:23 -04008069 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04008070
Bill Hollings542e8c32017-05-22 13:38:23 -04008071 case OpImageQuerySamples:
Hans-Kristian Arntzenf1752e52018-06-28 22:57:52 +02008072 MSL_ImgQry(samples);
Bill Hollings542e8c32017-05-22 13:38:23 -04008073 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04008074
Chip Davis9919fbb2018-09-29 19:07:16 -05008075 case OpImage:
8076 {
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008077 uint32_t result_type = ops[0];
Chip Davis9919fbb2018-09-29 19:07:16 -05008078 uint32_t id = ops[1];
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008079 auto *combined = maybe_get<SPIRCombinedImageSampler>(ops[2]);
Chip Davis9919fbb2018-09-29 19:07:16 -05008080
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008081 if (combined)
Chip Davis9919fbb2018-09-29 19:07:16 -05008082 {
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008083 auto &e = emit_op(result_type, id, to_expression(combined->image), true, true);
8084 auto *var = maybe_get_backing_variable(combined->image);
8085 if (var)
8086 e.loaded_from = var->self;
8087 }
8088 else
8089 {
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008090 auto *var = maybe_get_backing_variable(ops[2]);
Chip Davis39dce882019-08-02 15:11:19 -05008091 SPIRExpression *e;
8092 if (var && has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler))
8093 e = &emit_op(result_type, id, join(to_expression(ops[2]), ".plane0"), true, true);
8094 else
8095 e = &emit_op(result_type, id, to_expression(ops[2]), true, true);
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02008096 if (var)
Chip Davis39dce882019-08-02 15:11:19 -05008097 e->loaded_from = var->self;
Chip Davis9919fbb2018-09-29 19:07:16 -05008098 }
8099 break;
8100 }
8101
Bill Hollings542e8c32017-05-22 13:38:23 -04008102 // Casting
8103 case OpQuantizeToF16:
8104 {
8105 uint32_t result_type = ops[0];
8106 uint32_t id = ops[1];
8107 uint32_t arg = ops[2];
Bill Hollingsa2671e32021-09-24 14:41:15 -04008108 string exp = join("spvQuantizeToF16(", to_expression(arg), ")");
Bill Hollings542e8c32017-05-22 13:38:23 -04008109 emit_op(result_type, id, exp, should_forward(arg));
8110 break;
8111 }
8112
Chip Daviseb89c3a2019-02-03 23:58:46 -06008113 case OpInBoundsAccessChain:
8114 case OpAccessChain:
8115 case OpPtrAccessChain:
Chip Davise75add42019-02-05 18:13:26 -06008116 if (is_tessellation_shader())
Chip Daviseb89c3a2019-02-03 23:58:46 -06008117 {
Chip Davise75add42019-02-05 18:13:26 -06008118 if (!emit_tessellation_access_chain(ops, instruction.length))
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01008119 CompilerGLSL::emit_instruction(instruction);
Chip Daviseb89c3a2019-02-03 23:58:46 -06008120 }
Hans-Kristian Arntzen878c5022019-02-14 09:28:17 +01008121 else
8122 CompilerGLSL::emit_instruction(instruction);
Chip Davisaca9b682020-11-02 20:56:46 -06008123 fix_up_interpolant_access_chain(ops, instruction.length);
Chip Daviseb89c3a2019-02-03 23:58:46 -06008124 break;
8125
Bill Hollings1e84a372017-08-12 00:21:13 -04008126 case OpStore:
Chip Davis80954342019-02-20 00:33:46 -06008127 if (is_out_of_bounds_tessellation_level(ops[0]))
8128 break;
8129
Bill Hollings1c180782017-11-05 21:34:42 -05008130 if (maybe_emit_array_assignment(ops[0], ops[1]))
8131 break;
8132
8133 CompilerGLSL::emit_instruction(instruction);
Bill Hollings1e84a372017-08-12 00:21:13 -04008134 break;
Bill Hollings1c180782017-11-05 21:34:42 -05008135
8136 // Compute barriers
8137 case OpMemoryBarrier:
8138 emit_barrier(0, ops[0], ops[1]);
8139 break;
8140
8141 case OpControlBarrier:
8142 // In GLSL a memory barrier is often followed by a control barrier.
8143 // But in MSL, memory barriers are also control barriers, so don't
8144 // emit a simple control barrier if a memory barrier has just been emitted.
8145 if (previous_instruction_opcode != OpMemoryBarrier)
8146 emit_barrier(ops[0], ops[1], ops[2]);
8147 break;
Bill Hollings1e84a372017-08-12 00:21:13 -04008148
Hans-Kristian Arntzenf8b084d2019-07-01 10:57:27 +02008149 case OpOuterProduct:
8150 {
8151 uint32_t result_type = ops[0];
8152 uint32_t id = ops[1];
8153 uint32_t a = ops[2];
8154 uint32_t b = ops[3];
8155
8156 auto &type = get<SPIRType>(result_type);
8157 string expr = type_to_glsl_constructor(type);
8158 expr += "(";
8159 for (uint32_t col = 0; col < type.columns; col++)
8160 {
Bill Hollings974a0812021-10-21 16:11:33 -04008161 expr += to_enclosed_unpacked_expression(a);
Hans-Kristian Arntzenf8b084d2019-07-01 10:57:27 +02008162 expr += " * ";
8163 expr += to_extract_component_expression(b, col);
8164 if (col + 1 < type.columns)
8165 expr += ", ";
8166 }
8167 expr += ")";
8168 emit_op(result_type, id, expr, should_forward(a) && should_forward(b));
8169 inherit_expression_dependencies(id, a);
8170 inherit_expression_dependencies(id, b);
8171 break;
8172 }
Bill Hollings8f6df772017-05-19 18:14:08 -04008173
Lukas Hermanns36eab882019-09-17 11:40:01 -04008174 case OpVectorTimesMatrix:
8175 case OpMatrixTimesVector:
8176 {
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02008177 if (!msl_options.invariant_float_math && !has_decoration(ops[1], DecorationNoContraction))
Hans-Kristian Arntzenba4b31e2019-10-24 11:34:52 +02008178 {
8179 CompilerGLSL::emit_instruction(instruction);
8180 break;
8181 }
8182
Lukas Hermanns36eab882019-09-17 11:40:01 -04008183 // If the matrix needs transpose, just flip the multiply order.
8184 auto *e = maybe_get<SPIRExpression>(ops[opcode == OpMatrixTimesVector ? 2 : 3]);
8185 if (e && e->need_transpose)
8186 {
8187 e->need_transpose = false;
8188 string expr;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008189
Lukas Hermanns36eab882019-09-17 11:40:01 -04008190 if (opcode == OpMatrixTimesVector)
8191 {
Hans-Kristian Arntzenba4b31e2019-10-24 11:34:52 +02008192 expr = join("spvFMulVectorMatrix(", to_enclosed_unpacked_expression(ops[3]), ", ",
8193 to_unpacked_row_major_matrix_expression(ops[2]), ")");
Lukas Hermanns36eab882019-09-17 11:40:01 -04008194 }
8195 else
8196 {
Hans-Kristian Arntzenba4b31e2019-10-24 11:34:52 +02008197 expr = join("spvFMulMatrixVector(", to_unpacked_row_major_matrix_expression(ops[3]), ", ",
8198 to_enclosed_unpacked_expression(ops[2]), ")");
Lukas Hermanns36eab882019-09-17 11:40:01 -04008199 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008200
Lukas Hermanns36eab882019-09-17 11:40:01 -04008201 bool forward = should_forward(ops[2]) && should_forward(ops[3]);
8202 emit_op(ops[0], ops[1], expr, forward);
8203 e->need_transpose = true;
8204 inherit_expression_dependencies(ops[1], ops[2]);
8205 inherit_expression_dependencies(ops[1], ops[3]);
8206 }
Hans-Kristian Arntzenba4b31e2019-10-24 11:34:52 +02008207 else
Lukas Hermannsffbd8012019-10-09 11:22:25 -04008208 {
8209 if (opcode == OpMatrixTimesVector)
8210 MSL_BFOP(spvFMulMatrixVector);
8211 else
8212 MSL_BFOP(spvFMulVectorMatrix);
8213 }
Lukas Hermanns36eab882019-09-17 11:40:01 -04008214 break;
8215 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008216
Lukas Hermanns36eab882019-09-17 11:40:01 -04008217 case OpMatrixTimesMatrix:
8218 {
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +02008219 if (!msl_options.invariant_float_math && !has_decoration(ops[1], DecorationNoContraction))
Hans-Kristian Arntzen2ca725a2019-10-24 11:37:22 +02008220 {
8221 CompilerGLSL::emit_instruction(instruction);
8222 break;
8223 }
8224
Lukas Hermanns36eab882019-09-17 11:40:01 -04008225 auto *a = maybe_get<SPIRExpression>(ops[2]);
8226 auto *b = maybe_get<SPIRExpression>(ops[3]);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008227
Lukas Hermanns36eab882019-09-17 11:40:01 -04008228 // If both matrices need transpose, we can multiply in flipped order and tag the expression as transposed.
8229 // a^T * b^T = (b * a)^T.
8230 if (a && b && a->need_transpose && b->need_transpose)
8231 {
8232 a->need_transpose = false;
8233 b->need_transpose = false;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008234
Hans-Kristian Arntzen39bd5f12019-10-28 12:55:14 +01008235 auto expr =
8236 join("spvFMulMatrixMatrix(", enclose_expression(to_unpacked_row_major_matrix_expression(ops[3])), ", ",
8237 enclose_expression(to_unpacked_row_major_matrix_expression(ops[2])), ")");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008238
Lukas Hermanns36eab882019-09-17 11:40:01 -04008239 bool forward = should_forward(ops[2]) && should_forward(ops[3]);
8240 auto &e = emit_op(ops[0], ops[1], expr, forward);
8241 e.need_transpose = true;
8242 a->need_transpose = true;
8243 b->need_transpose = true;
8244 inherit_expression_dependencies(ops[1], ops[2]);
8245 inherit_expression_dependencies(ops[1], ops[3]);
8246 }
Lukas Hermanns36eab882019-09-17 11:40:01 -04008247 else
Hans-Kristian Arntzen2ca725a2019-10-24 11:37:22 +02008248 MSL_BFOP(spvFMulMatrixMatrix);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008249
Lukas Hermanns36eab882019-09-17 11:40:01 -04008250 break;
8251 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008252
Chip Daviscf2a8902018-11-13 14:11:50 -06008253 case OpIAddCarry:
8254 case OpISubBorrow:
8255 {
8256 uint32_t result_type = ops[0];
8257 uint32_t result_id = ops[1];
8258 uint32_t op0 = ops[2];
8259 uint32_t op1 = ops[3];
Chip Daviscf2a8902018-11-13 14:11:50 -06008260 auto &type = get<SPIRType>(result_type);
Hans-Kristian Arntzenc3e8e722019-07-26 11:16:43 +02008261 emit_uninitialized_temporary_expression(result_type, result_id);
Chip Daviscf2a8902018-11-13 14:11:50 -06008262
8263 auto &res_type = get<SPIRType>(type.member_types[1]);
8264 if (opcode == OpIAddCarry)
8265 {
Bill Hollings974a0812021-10-21 16:11:33 -04008266 statement(to_expression(result_id), ".", to_member_name(type, 0), " = ",
8267 to_enclosed_unpacked_expression(op0), " + ", to_enclosed_unpacked_expression(op1), ";");
Chip Daviscf2a8902018-11-13 14:11:50 -06008268 statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
Bill Hollings974a0812021-10-21 16:11:33 -04008269 "(1), ", type_to_glsl(res_type), "(0), ", to_unpacked_expression(result_id), ".", to_member_name(type, 0),
8270 " >= max(", to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), "));");
Chip Daviscf2a8902018-11-13 14:11:50 -06008271 }
8272 else
8273 {
Bill Hollings974a0812021-10-21 16:11:33 -04008274 statement(to_expression(result_id), ".", to_member_name(type, 0), " = ", to_enclosed_unpacked_expression(op0), " - ",
8275 to_enclosed_unpacked_expression(op1), ";");
Chip Daviscf2a8902018-11-13 14:11:50 -06008276 statement(to_expression(result_id), ".", to_member_name(type, 1), " = select(", type_to_glsl(res_type),
Bill Hollings974a0812021-10-21 16:11:33 -04008277 "(1), ", type_to_glsl(res_type), "(0), ", to_enclosed_unpacked_expression(op0),
8278 " >= ", to_enclosed_unpacked_expression(op1), ");");
Chip Daviscf2a8902018-11-13 14:11:50 -06008279 }
8280 break;
8281 }
8282
8283 case OpUMulExtended:
8284 case OpSMulExtended:
8285 {
8286 uint32_t result_type = ops[0];
8287 uint32_t result_id = ops[1];
8288 uint32_t op0 = ops[2];
8289 uint32_t op1 = ops[3];
Chip Daviscf2a8902018-11-13 14:11:50 -06008290 auto &type = get<SPIRType>(result_type);
Hans-Kristian Arntzenc3e8e722019-07-26 11:16:43 +02008291 emit_uninitialized_temporary_expression(result_type, result_id);
Chip Daviscf2a8902018-11-13 14:11:50 -06008292
Bill Hollings974a0812021-10-21 16:11:33 -04008293 statement(to_expression(result_id), ".", to_member_name(type, 0), " = ",
8294 to_enclosed_unpacked_expression(op0), " * ", to_enclosed_unpacked_expression(op1), ";");
8295 statement(to_expression(result_id), ".", to_member_name(type, 1), " = mulhi(",
8296 to_unpacked_expression(op0), ", ", to_unpacked_expression(op1), ");");
Chip Daviscf2a8902018-11-13 14:11:50 -06008297 break;
8298 }
8299
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02008300 case OpArrayLength:
8301 {
8302 auto &type = expression_type(ops[2]);
8303 uint32_t offset = type_struct_member_offset(type, ops[3]);
8304 uint32_t stride = type_struct_member_array_stride(type, ops[3]);
8305
8306 auto expr = join("(", to_buffer_size_expression(ops[2]), " - ", offset, ") / ", stride);
8307 emit_op(ops[0], ops[1], expr, true);
8308 break;
8309 }
8310
Chip Davisbc646572019-07-11 18:20:19 -05008311 // SPV_INTEL_shader_integer_functions2
8312 case OpUCountLeadingZerosINTEL:
8313 MSL_UFOP(clz);
8314 break;
8315
8316 case OpUCountTrailingZerosINTEL:
8317 MSL_UFOP(ctz);
8318 break;
8319
8320 case OpAbsISubINTEL:
8321 case OpAbsUSubINTEL:
8322 MSL_BFOP(absdiff);
8323 break;
8324
8325 case OpIAddSatINTEL:
8326 case OpUAddSatINTEL:
8327 MSL_BFOP(addsat);
8328 break;
8329
8330 case OpIAverageINTEL:
8331 case OpUAverageINTEL:
8332 MSL_BFOP(hadd);
8333 break;
8334
8335 case OpIAverageRoundedINTEL:
8336 case OpUAverageRoundedINTEL:
8337 MSL_BFOP(rhadd);
8338 break;
8339
8340 case OpISubSatINTEL:
8341 case OpUSubSatINTEL:
8342 MSL_BFOP(subsat);
8343 break;
8344
8345 case OpIMul32x16INTEL:
8346 {
8347 uint32_t result_type = ops[0];
8348 uint32_t id = ops[1];
8349 uint32_t a = ops[2], b = ops[3];
8350 bool forward = should_forward(a) && should_forward(b);
Bill Hollings974a0812021-10-21 16:11:33 -04008351 emit_op(result_type, id, join("int(short(", to_unpacked_expression(a), ")) * int(short(", to_unpacked_expression(b), "))"), forward);
Chip Davisbc646572019-07-11 18:20:19 -05008352 inherit_expression_dependencies(id, a);
8353 inherit_expression_dependencies(id, b);
8354 break;
8355 }
8356
8357 case OpUMul32x16INTEL:
8358 {
8359 uint32_t result_type = ops[0];
8360 uint32_t id = ops[1];
8361 uint32_t a = ops[2], b = ops[3];
8362 bool forward = should_forward(a) && should_forward(b);
Bill Hollings974a0812021-10-21 16:11:33 -04008363 emit_op(result_type, id, join("uint(ushort(", to_unpacked_expression(a), ")) * uint(ushort(", to_unpacked_expression(b), "))"), forward);
Chip Davisbc646572019-07-11 18:20:19 -05008364 inherit_expression_dependencies(id, a);
8365 inherit_expression_dependencies(id, b);
8366 break;
8367 }
8368
Chip Davis2219c4a2020-09-28 23:07:55 -05008369 // SPV_EXT_demote_to_helper_invocation
8370 case OpDemoteToHelperInvocationEXT:
8371 if (!msl_options.supports_msl_version(2, 3))
8372 SPIRV_CROSS_THROW("discard_fragment() does not formally have demote semantics until MSL 2.3.");
8373 CompilerGLSL::emit_instruction(instruction);
8374 break;
8375
Chip Davis50dce102019-07-13 15:57:33 -05008376 case OpIsHelperInvocationEXT:
Chip Davis2219c4a2020-09-28 23:07:55 -05008377 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
8378 SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.3 on iOS.");
Chip Davis50dce102019-07-13 15:57:33 -05008379 else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
Chip Davis2219c4a2020-09-28 23:07:55 -05008380 SPIRV_CROSS_THROW("simd_is_helper_thread() requires MSL 2.1 on macOS.");
Chip Davis12a86542019-07-18 17:32:35 -05008381 emit_op(ops[0], ops[1], "simd_is_helper_thread()", false);
Chip Davis50dce102019-07-13 15:57:33 -05008382 break;
8383
Chip Davis2eff4202019-08-04 00:07:20 -05008384 case OpBeginInvocationInterlockEXT:
8385 case OpEndInvocationInterlockEXT:
8386 if (!msl_options.supports_msl_version(2, 0))
8387 SPIRV_CROSS_THROW("Raster order groups require MSL 2.0.");
8388 break; // Nothing to do in the body
8389
丛越d52ec1e2021-10-21 17:46:45 +08008390 case OpConvertUToAccelerationStructureKHR:
丛越2895a432021-10-21 19:01:38 +08008391 SPIRV_CROSS_THROW("ConvertUToAccelerationStructure is not supported in MSL.");
丛越2895a432021-10-21 19:01:38 +08008392 case OpRayQueryGetIntersectionInstanceShaderBindingTableRecordOffsetKHR:
8393 SPIRV_CROSS_THROW("BindingTableRecordOffset is not supported in MSL.");
丛越d52ec1e2021-10-21 17:46:45 +08008394
丛越597f29d2021-10-19 18:45:10 +08008395 case OpRayQueryInitializeKHR:
8396 {
8397 flush_variable_declaration(ops[0]);
8398
丛越597f29d2021-10-19 18:45:10 +08008399 statement(to_expression(ops[0]), ".reset(", "ray(", to_expression(ops[4]), ", ", to_expression(ops[6]), ", ",
8400 to_expression(ops[5]), ", ", to_expression(ops[7]), "), ", to_expression(ops[1]),
丛越d52ec1e2021-10-21 17:46:45 +08008401 ", intersection_params());");
丛越597f29d2021-10-19 18:45:10 +08008402 break;
8403 }
8404 case OpRayQueryProceedKHR:
8405 {
8406 flush_variable_declaration(ops[0]);
8407 emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".next()"), false);
8408 break;
8409 }
丛越d52ec1e2021-10-21 17:46:45 +08008410#define MSL_RAY_QUERY_IS_CANDIDATE get<SPIRConstant>(ops[3]).scalar_i32() == 0
丛越597f29d2021-10-19 18:45:10 +08008411
8412#define MSL_RAY_QUERY_GET_OP(op, msl_op) \
8413 case OpRayQueryGet##op##KHR: \
8414 flush_variable_declaration(ops[2]); \
8415 emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_" #msl_op "()"), false); \
8416 break
8417
8418#define MSL_RAY_QUERY_OP_INNER2(op, msl_prefix, msl_op) \
8419 case OpRayQueryGet##op##KHR: \
8420 flush_variable_declaration(ops[2]); \
8421 if (MSL_RAY_QUERY_IS_CANDIDATE) \
8422 emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_candidate_" #msl_op "()"), false); \
8423 else \
8424 emit_op(ops[0], ops[1], join(to_expression(ops[2]), #msl_prefix "_committed_" #msl_op "()"), false); \
8425 break
8426
8427#define MSL_RAY_QUERY_GET_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .get, msl_op)
8428#define MSL_RAY_QUERY_IS_OP2(op, msl_op) MSL_RAY_QUERY_OP_INNER2(op, .is, msl_op)
8429
8430 MSL_RAY_QUERY_GET_OP(RayTMin, ray_min_distance);
8431 MSL_RAY_QUERY_GET_OP(WorldRayOrigin, world_space_ray_direction);
8432 MSL_RAY_QUERY_GET_OP(WorldRayDirection, world_space_ray_origin);
8433 MSL_RAY_QUERY_GET_OP2(IntersectionInstanceId, instance_id);
8434 MSL_RAY_QUERY_GET_OP2(IntersectionInstanceCustomIndex, user_instance_id);
8435 MSL_RAY_QUERY_GET_OP2(IntersectionBarycentrics, triangle_barycentric_coord);
8436 MSL_RAY_QUERY_GET_OP2(IntersectionPrimitiveIndex, primitive_id);
8437 MSL_RAY_QUERY_GET_OP2(IntersectionGeometryIndex, geometry_id);
8438 MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayOrigin, ray_origin);
8439 MSL_RAY_QUERY_GET_OP2(IntersectionObjectRayDirection, ray_direction);
8440 MSL_RAY_QUERY_GET_OP2(IntersectionObjectToWorld, object_to_world_transform);
8441 MSL_RAY_QUERY_GET_OP2(IntersectionWorldToObject, world_to_object_transform);
8442 MSL_RAY_QUERY_IS_OP2(IntersectionFrontFace, triangle_front_facing);
8443
8444 case OpRayQueryGetIntersectionTypeKHR:
8445 flush_variable_declaration(ops[2]);
8446 if (MSL_RAY_QUERY_IS_CANDIDATE)
丛越d52ec1e2021-10-21 17:46:45 +08008447 emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_candidate_intersection_type()) - 1"),
丛越597f29d2021-10-19 18:45:10 +08008448 false);
8449 else
丛越d52ec1e2021-10-21 17:46:45 +08008450 emit_op(ops[0], ops[1], join("uint(", to_expression(ops[2]), ".get_committed_intersection_type())"), false);
丛越597f29d2021-10-19 18:45:10 +08008451 break;
8452 case OpRayQueryGetIntersectionTKHR:
8453 flush_variable_declaration(ops[2]);
8454 if (MSL_RAY_QUERY_IS_CANDIDATE)
8455 emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_candidate_triangle_distance()"), false);
8456 else
8457 emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".get_committed_distance()"), false);
8458 break;
8459 case OpRayQueryGetIntersectionCandidateAABBOpaqueKHR:
8460 {
8461 flush_variable_declaration(ops[0]);
8462 emit_op(ops[0], ops[1], join(to_expression(ops[2]), ".is_candidate_non_opaque_bounding_box()"), false);
8463 break;
8464 }
8465 case OpRayQueryConfirmIntersectionKHR:
8466 flush_variable_declaration(ops[0]);
Hans-Kristian Arntzen5afb3d32021-10-21 21:53:15 +02008467 statement(to_expression(ops[0]), ".commit_triangle_intersection();");
丛越597f29d2021-10-19 18:45:10 +08008468 break;
8469 case OpRayQueryGenerateIntersectionKHR:
8470 flush_variable_declaration(ops[0]);
8471 statement(to_expression(ops[0]), ".commit_bounding_box_intersection(", to_expression(ops[1]), ");");
8472 break;
8473 case OpRayQueryTerminateKHR:
8474 flush_variable_declaration(ops[0]);
8475 statement(to_expression(ops[0]), ".abort();");
8476 break;
8477#undef MSL_RAY_QUERY_GET_OP
8478#undef MSL_RAY_QUERY_IS_CANDIDATE
8479#undef MSL_RAY_QUERY_IS_OP2
8480#undef MSL_RAY_QUERY_GET_OP2
8481#undef MSL_RAY_QUERY_OP_INNER2
Bill Hollingsf5f91042016-10-27 18:47:17 -04008482 default:
8483 CompilerGLSL::emit_instruction(instruction);
8484 break;
8485 }
Bill Hollings1c180782017-11-05 21:34:42 -05008486
8487 previous_instruction_opcode = opcode;
8488}
8489
Hans-Kristian Arntzen275974e2020-06-04 15:50:28 +02008490void CompilerMSL::emit_texture_op(const Instruction &i, bool sparse)
Mark Satterthwaite32557e92019-08-14 10:46:23 -04008491{
Hans-Kristian Arntzen275974e2020-06-04 15:50:28 +02008492 if (sparse)
8493 SPIRV_CROSS_THROW("Sparse feedback not yet supported in MSL.");
8494
Chip Davisc20d5942020-10-27 21:42:33 -05008495 if (msl_options.use_framebuffer_fetch_subpasses)
Mark Satterthwaite97a66ff2019-08-14 10:48:47 -04008496 {
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04008497 auto *ops = stream(i);
8498
8499 uint32_t result_type_id = ops[0];
8500 uint32_t id = ops[1];
8501 uint32_t img = ops[2];
8502
8503 auto &type = expression_type(img);
8504 auto &imgtype = get<SPIRType>(type.self);
8505
8506 // Use Metal's native frame-buffer fetch API for subpass inputs.
8507 if (imgtype.image.dim == DimSubpassData)
8508 {
Hans-Kristian Arntzenb4338362019-10-24 11:48:29 +02008509 // Subpass inputs cannot be invalidated,
8510 // so just forward the expression directly.
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04008511 string expr = to_expression(img);
Hans-Kristian Arntzenb4338362019-10-24 11:48:29 +02008512 emit_op(result_type_id, id, expr, true);
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04008513 return;
8514 }
Mark Satterthwaite97a66ff2019-08-14 10:48:47 -04008515 }
Mark Satterthwaite97a66ff2019-08-14 10:48:47 -04008516
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04008517 // Fallback to default implementation
Hans-Kristian Arntzen275974e2020-06-04 15:50:28 +02008518 CompilerGLSL::emit_texture_op(i, sparse);
Mark Satterthwaite32557e92019-08-14 10:46:23 -04008519}
Mark Satterthwaite32557e92019-08-14 10:46:23 -04008520
Bill Hollings1c180782017-11-05 21:34:42 -05008521void CompilerMSL::emit_barrier(uint32_t id_exe_scope, uint32_t id_mem_scope, uint32_t id_mem_sem)
8522{
Chip Daviseb89c3a2019-02-03 23:58:46 -06008523 if (get_execution_model() != ExecutionModelGLCompute && get_execution_model() != ExecutionModelTessellationControl)
Bill Hollings1c180782017-11-05 21:34:42 -05008524 return;
8525
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +02008526 uint32_t exe_scope = id_exe_scope ? evaluate_constant_u32(id_exe_scope) : uint32_t(ScopeInvocation);
8527 uint32_t mem_scope = id_mem_scope ? evaluate_constant_u32(id_mem_scope) : uint32_t(ScopeInvocation);
Chip Davis9d941572019-05-15 16:03:30 -05008528 // Use the wider of the two scopes (smaller value)
8529 exe_scope = min(exe_scope, mem_scope);
8530
Chip Davis68908352020-11-18 23:16:46 -06008531 if (msl_options.emulate_subgroups && exe_scope >= ScopeSubgroup && !id_mem_sem)
8532 // In this case, we assume a "subgroup" size of 1. The barrier, then, is a noop.
8533 return;
8534
Chip Davis9d941572019-05-15 16:03:30 -05008535 string bar_stmt;
8536 if ((msl_options.is_ios() && msl_options.supports_msl_version(1, 2)) || msl_options.supports_msl_version(2))
8537 bar_stmt = exe_scope < ScopeSubgroup ? "threadgroup_barrier" : "simdgroup_barrier";
8538 else
8539 bar_stmt = "threadgroup_barrier";
8540 bar_stmt += "(";
Bill Hollings1c180782017-11-05 21:34:42 -05008541
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +02008542 uint32_t mem_sem = id_mem_sem ? evaluate_constant_u32(id_mem_sem) : uint32_t(MemorySemanticsMaskNone);
Bill Hollings3fcdce02017-12-26 13:39:07 -05008543
Chip Davis9d941572019-05-15 16:03:30 -05008544 // Use the | operator to combine flags if we can.
8545 if (msl_options.supports_msl_version(1, 2))
8546 {
8547 string mem_flags = "";
Chip Daviseb89c3a2019-02-03 23:58:46 -06008548 // For tesc shaders, this also affects objects in the Output storage class.
8549 // Since in Metal, these are placed in a device buffer, we have to sync device memory here.
Chip Davis9d941572019-05-15 16:03:30 -05008550 if (get_execution_model() == ExecutionModelTessellationControl ||
8551 (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)))
8552 mem_flags += "mem_flags::mem_device";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008553
Lukas Hermanns50ac6862019-09-18 14:03:54 -04008554 // Fix tessellation patch function processing
Mark Satterthwaite42b8a622019-08-14 10:51:48 -04008555 if (get_execution_model() == ExecutionModelTessellationControl ||
Hans-Kristian Arntzen00d5c782019-12-04 15:30:07 +01008556 (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
Chip Davis9d941572019-05-15 16:03:30 -05008557 {
8558 if (!mem_flags.empty())
8559 mem_flags += " | ";
8560 mem_flags += "mem_flags::mem_threadgroup";
8561 }
8562 if (mem_sem & MemorySemanticsImageMemoryMask)
8563 {
8564 if (!mem_flags.empty())
8565 mem_flags += " | ";
8566 mem_flags += "mem_flags::mem_texture";
8567 }
8568
8569 if (mem_flags.empty())
8570 mem_flags = "mem_flags::mem_none";
8571
8572 bar_stmt += mem_flags;
8573 }
Bill Hollings3fcdce02017-12-26 13:39:07 -05008574 else
Chip Davis9d941572019-05-15 16:03:30 -05008575 {
8576 if ((mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask)) &&
Hans-Kristian Arntzen00d5c782019-12-04 15:30:07 +01008577 (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask)))
Chip Davis9d941572019-05-15 16:03:30 -05008578 bar_stmt += "mem_flags::mem_device_and_threadgroup";
8579 else if (mem_sem & (MemorySemanticsUniformMemoryMask | MemorySemanticsCrossWorkgroupMemoryMask))
8580 bar_stmt += "mem_flags::mem_device";
Hans-Kristian Arntzen00d5c782019-12-04 15:30:07 +01008581 else if (mem_sem & (MemorySemanticsSubgroupMemoryMask | MemorySemanticsWorkgroupMemoryMask))
Chip Davis9d941572019-05-15 16:03:30 -05008582 bar_stmt += "mem_flags::mem_threadgroup";
8583 else if (mem_sem & MemorySemanticsImageMemoryMask)
8584 bar_stmt += "mem_flags::mem_texture";
8585 else
8586 bar_stmt += "mem_flags::mem_none";
8587 }
Bill Hollings1c180782017-11-05 21:34:42 -05008588
Bill Hollings1c180782017-11-05 21:34:42 -05008589 bar_stmt += ");";
8590
8591 statement(bar_stmt);
Hans-Kristian Arntzen938c7de2018-03-12 17:34:54 +01008592
8593 assert(current_emitting_block);
8594 flush_control_dependent_expressions(current_emitting_block->self);
8595 flush_all_active_variables();
Bill Hollingsf5f91042016-10-27 18:47:17 -04008596}
8597
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008598static bool storage_class_array_is_thread(StorageClass storage)
8599{
8600 switch (storage)
8601 {
8602 case StorageClassInput:
8603 case StorageClassOutput:
8604 case StorageClassGeneric:
8605 case StorageClassFunction:
8606 case StorageClassPrivate:
8607 return true;
8608
8609 default:
8610 return false;
8611 }
8612}
8613
8614void CompilerMSL::emit_array_copy(const string &lhs, uint32_t lhs_id, uint32_t rhs_id,
8615 StorageClass lhs_storage, StorageClass rhs_storage)
Hans-Kristian Arntzen00ccd592018-02-05 12:37:41 +01008616{
Lukas Hermanns50ac6862019-09-18 14:03:54 -04008617 // Allow Metal to use the array<T> template to make arrays a value type.
8618 // This, however, cannot be used for threadgroup address specifiers, so consider the custom array copy as fallback.
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008619 bool lhs_is_thread_storage = storage_class_array_is_thread(lhs_storage);
8620 bool rhs_is_thread_storage = storage_class_array_is_thread(rhs_storage);
8621
8622 bool lhs_is_array_template = lhs_is_thread_storage;
8623 bool rhs_is_array_template = rhs_is_thread_storage;
8624
8625 // Special considerations for stage IO variables.
8626 // If the variable is actually backed by non-user visible device storage, we use array templates for those.
Hans-Kristian Arntzen2eea6a52021-08-23 13:23:40 +02008627 //
8628 // Another special consideration is given to thread local variables which happen to have Offset decorations
8629 // applied to them. Block-like types do not use array templates, so we need to force POD path if we detect
8630 // these scenarios. This check isn't perfect since it would be technically possible to mix and match these things,
8631 // and for a fully correct solution we might have to track array template state through access chains as well,
8632 // but for all reasonable use cases, this should suffice.
8633 // This special case should also only apply to Function/Private storage classes.
8634 // We should not check backing variable for temporaries.
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008635 auto *lhs_var = maybe_get_backing_variable(lhs_id);
8636 if (lhs_var && lhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(lhs_var->storage))
8637 lhs_is_array_template = true;
Hans-Kristian Arntzen2eea6a52021-08-23 13:23:40 +02008638 else if (lhs_var && (lhs_storage == StorageClassFunction || lhs_storage == StorageClassPrivate) &&
8639 type_is_block_like(get<SPIRType>(lhs_var->basetype)))
8640 lhs_is_array_template = false;
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008641
8642 auto *rhs_var = maybe_get_backing_variable(rhs_id);
8643 if (rhs_var && rhs_storage == StorageClassStorageBuffer && storage_class_array_is_thread(rhs_var->storage))
8644 rhs_is_array_template = true;
Hans-Kristian Arntzen2eea6a52021-08-23 13:23:40 +02008645 else if (rhs_var && (rhs_storage == StorageClassFunction || rhs_storage == StorageClassPrivate) &&
8646 type_is_block_like(get<SPIRType>(rhs_var->basetype)))
8647 rhs_is_array_template = false;
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02008648
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008649 // If threadgroup storage qualifiers are *not* used:
Lukas Hermanns51be6012019-09-17 15:10:39 -04008650 // Avoid spvCopy* wrapper functions; Otherwise, spvUnsafeArray<> template cannot be used with that storage qualifier.
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008651 if (lhs_is_array_template && rhs_is_array_template && !using_builtin_array())
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +02008652 {
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008653 statement(lhs, " = ", to_expression(rhs_id), ";");
Hans-Kristian Arntzen23db7442019-04-09 12:28:46 +02008654 }
Chip Davis39dce882019-08-02 15:11:19 -05008655 else
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008656 {
8657 // Assignment from an array initializer is fine.
8658 auto &type = expression_type(rhs_id);
8659 auto *var = maybe_get_backing_variable(rhs_id);
Hans-Kristian Arntzen23db7442019-04-09 12:28:46 +02008660
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008661 // Unfortunately, we cannot template on address space in MSL,
8662 // so explicit address space redirection it is ...
8663 bool is_constant = false;
8664 if (ir.ids[rhs_id].get_type() == TypeConstant)
8665 {
8666 is_constant = true;
8667 }
8668 else if (var && var->remapped_variable && var->statically_assigned &&
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008669 ir.ids[var->static_expression].get_type() == TypeConstant)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008670 {
8671 is_constant = true;
8672 }
chirsz-ever90c25222022-01-05 17:45:21 +08008673 else if (rhs_storage == StorageClassUniform || rhs_storage == StorageClassUniformConstant)
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02008674 {
8675 is_constant = true;
8676 }
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02008677
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008678 // For the case where we have OpLoad triggering an array copy,
8679 // we cannot easily detect this case ahead of time since it's
8680 // context dependent. We might have to force a recompile here
8681 // if this is the only use of array copies in our shader.
8682 if (type.array.size() > 1)
8683 {
Corentin Wallezbcd71532020-09-04 10:04:25 +02008684 if (type.array.size() > kArrayCopyMultidimMax)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008685 SPIRV_CROSS_THROW("Cannot support this many dimensions for arrays of arrays.");
8686 auto func = static_cast<SPVFuncImpl>(SPVFuncImplArrayCopyMultidimBase + type.array.size());
8687 add_spv_func_and_recompile(func);
8688 }
8689 else
8690 add_spv_func_and_recompile(SPVFuncImplArrayCopy);
Hans-Kristian Arntzen9436cd32019-08-27 13:16:16 +02008691
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008692 const char *tag = nullptr;
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008693 if (lhs_is_thread_storage && is_constant)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008694 tag = "FromConstantToStack";
8695 else if (lhs_storage == StorageClassWorkgroup && is_constant)
8696 tag = "FromConstantToThreadGroup";
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008697 else if (lhs_is_thread_storage && rhs_is_thread_storage)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008698 tag = "FromStackToStack";
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008699 else if (lhs_storage == StorageClassWorkgroup && rhs_is_thread_storage)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008700 tag = "FromStackToThreadGroup";
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008701 else if (lhs_is_thread_storage && rhs_storage == StorageClassWorkgroup)
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008702 tag = "FromThreadGroupToStack";
8703 else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassWorkgroup)
8704 tag = "FromThreadGroupToThreadGroup";
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02008705 else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassStorageBuffer)
8706 tag = "FromDeviceToDevice";
8707 else if (lhs_storage == StorageClassStorageBuffer && is_constant)
8708 tag = "FromConstantToDevice";
8709 else if (lhs_storage == StorageClassStorageBuffer && rhs_storage == StorageClassWorkgroup)
8710 tag = "FromThreadGroupToDevice";
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008711 else if (lhs_storage == StorageClassStorageBuffer && rhs_is_thread_storage)
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02008712 tag = "FromStackToDevice";
8713 else if (lhs_storage == StorageClassWorkgroup && rhs_storage == StorageClassStorageBuffer)
8714 tag = "FromDeviceToThreadGroup";
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008715 else if (lhs_is_thread_storage && rhs_storage == StorageClassStorageBuffer)
Hans-Kristian Arntzen03d4bce2020-06-18 11:37:24 +02008716 tag = "FromDeviceToStack";
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008717 else
8718 SPIRV_CROSS_THROW("Unknown storage class used for copying arrays.");
8719
Lukas Hermanns51be6012019-09-17 15:10:39 -04008720 // Pass internal array of spvUnsafeArray<> into wrapper functions
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008721 if (lhs_is_array_template && rhs_is_array_template && !msl_options.force_native_arrays)
8722 statement("spvArrayCopy", tag, type.array.size(), "(", lhs, ".elements, ", to_expression(rhs_id), ".elements);");
8723 if (lhs_is_array_template && !msl_options.force_native_arrays)
Lukas Hermanns51be6012019-09-17 15:10:39 -04008724 statement("spvArrayCopy", tag, type.array.size(), "(", lhs, ".elements, ", to_expression(rhs_id), ");");
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008725 else if (rhs_is_array_template && !msl_options.force_native_arrays)
Lukas Hermanns51be6012019-09-17 15:10:39 -04008726 statement("spvArrayCopy", tag, type.array.size(), "(", lhs, ", ", to_expression(rhs_id), ".elements);");
Mark Satterthwaited50659a2019-08-13 18:18:48 -04008727 else
8728 statement("spvArrayCopy", tag, type.array.size(), "(", lhs, ", ", to_expression(rhs_id), ");");
8729 }
Hans-Kristian Arntzen00ccd592018-02-05 12:37:41 +01008730}
8731
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +01008732uint32_t CompilerMSL::get_physical_tess_level_array_size(spv::BuiltIn builtin) const
8733{
8734 if (get_execution_mode_bitset().get(ExecutionModeTriangles))
8735 return builtin == BuiltInTessLevelInner ? 1 : 3;
8736 else
8737 return builtin == BuiltInTessLevelInner ? 2 : 4;
8738}
8739
Bill Hollings1c180782017-11-05 21:34:42 -05008740// Since MSL does not allow arrays to be copied via simple variable assignment,
8741// if the LHS and RHS represent an assignment of an entire array, it must be
8742// implemented by calling an array copy function.
8743// Returns whether the struct assignment was emitted.
8744bool CompilerMSL::maybe_emit_array_assignment(uint32_t id_lhs, uint32_t id_rhs)
8745{
Bill Hollings1c180782017-11-05 21:34:42 -05008746 // We only care about assignments of an entire array
8747 auto &type = expression_type(id_rhs);
8748 if (type.array.size() == 0)
8749 return false;
8750
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01008751 auto *var = maybe_get<SPIRVariable>(id_lhs);
Hans-Kristian Arntzend29f48e2018-07-05 13:25:57 +02008752
8753 // Is this a remapped, static constant? Don't do anything.
Hans-Kristian Arntzenffb753f2018-08-08 16:48:22 +02008754 if (var && var->remapped_variable && var->statically_assigned)
Hans-Kristian Arntzend29f48e2018-07-05 13:25:57 +02008755 return true;
8756
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02008757 if (ir.ids[id_rhs].get_type() == TypeConstant && var && var->deferred_declaration)
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +01008758 {
8759 // Special case, if we end up declaring a variable when assigning the constant array,
8760 // we can avoid the copy by directly assigning the constant expression.
8761 // This is likely necessary to be able to use a variable as a true look-up table, as it is unlikely
8762 // the compiler will be able to optimize the spvArrayCopy() into a constant LUT.
8763 // After a variable has been declared, we can no longer assign constant arrays in MSL unfortunately.
8764 statement(to_expression(id_lhs), " = ", constant_expression(get<SPIRConstant>(id_rhs)), ";");
8765 return true;
8766 }
8767
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +01008768 if (get_execution_model() == ExecutionModelTessellationControl &&
8769 has_decoration(id_lhs, DecorationBuiltIn))
8770 {
8771 auto builtin = BuiltIn(get_decoration(id_lhs, DecorationBuiltIn));
8772 // Need to manually unroll the array store.
8773 if (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter)
8774 {
8775 uint32_t array_size = get_physical_tess_level_array_size(builtin);
8776 if (array_size == 1)
8777 statement(to_expression(id_lhs), " = half(", to_expression(id_rhs), "[0]);");
8778 else
8779 {
8780 for (uint32_t i = 0; i < array_size; i++)
8781 statement(to_expression(id_lhs), "[", i, "] = half(", to_expression(id_rhs), "[", i, "]);");
8782 }
8783 return true;
8784 }
8785 }
8786
Bill Hollings1c180782017-11-05 21:34:42 -05008787 // Ensure the LHS variable has been declared
8788 auto *p_v_lhs = maybe_get_backing_variable(id_lhs);
8789 if (p_v_lhs)
8790 flush_variable_declaration(p_v_lhs->self);
8791
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +02008792 auto lhs_storage = get_expression_effective_storage_class(id_lhs);
8793 auto rhs_storage = get_expression_effective_storage_class(id_rhs);
8794 emit_array_copy(to_expression(id_lhs), id_lhs, id_rhs, lhs_storage, rhs_storage);
Bill Hollings1c180782017-11-05 21:34:42 -05008795 register_write(id_lhs);
8796
8797 return true;
Bill Hollings1e84a372017-08-12 00:21:13 -04008798}
8799
Bill Hollings8f6df772017-05-19 18:14:08 -04008800// Emits one of the atomic functions. In MSL, the atomic functions operate on pointers
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01008801void CompilerMSL::emit_atomic_func_op(uint32_t result_type, uint32_t result_id, const char *op, Op opcode,
8802 uint32_t mem_order_1, uint32_t mem_order_2, bool has_mem_order_2, uint32_t obj, uint32_t op1,
Chip Davis06edf802018-09-13 08:56:23 -05008803 bool op1_is_pointer, bool op1_is_literal, uint32_t op2)
Bill Hollings8f6df772017-05-19 18:14:08 -04008804{
Bill Hollings8f6df772017-05-19 18:14:08 -04008805 string exp = string(op) + "(";
8806
Chip Davisfc02b3d2019-01-08 12:54:40 -06008807 auto &type = get_pointee_type(expression_type(obj));
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01008808 auto expected_type = type.basetype;
8809 if (opcode == OpAtomicUMax || opcode == OpAtomicUMin)
8810 expected_type = to_unsigned_basetype(type.width);
8811 else if (opcode == OpAtomicSMax || opcode == OpAtomicSMin)
8812 expected_type = to_signed_basetype(type.width);
8813
8814 auto remapped_type = type;
8815 remapped_type.basetype = expected_type;
8816
Chip Davis058f1a02019-07-10 11:17:40 -05008817 exp += "(";
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008818 auto *var = maybe_get_backing_variable(obj);
8819 if (!var)
8820 SPIRV_CROSS_THROW("No backing variable for atomic operation.");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008821
Lukas Hermanns50ac6862019-09-18 14:03:54 -04008822 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04008823 const auto &res_type = get<SPIRType>(var->basetype);
8824 if (res_type.storage == StorageClassUniformConstant && res_type.basetype == SPIRType::Image)
8825 {
8826 exp += "device";
8827 }
8828 else
8829 {
Lukas Hermanns50ac6862019-09-18 14:03:54 -04008830 exp += get_argument_address_space(*var);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -04008831 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04008832
Bill Hollings8f6df772017-05-19 18:14:08 -04008833 exp += " atomic_";
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01008834 // For signed and unsigned min/max, we can signal this through the pointer type.
8835 // There is no other way, since C++ does not have explicit signage for atomics.
8836 exp += type_to_glsl(remapped_type);
Bill Hollings8f6df772017-05-19 18:14:08 -04008837 exp += "*)";
8838
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008839 exp += "&";
8840 exp += to_enclosed_expression(obj);
Bill Hollings8f6df772017-05-19 18:14:08 -04008841
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008842 bool is_atomic_compare_exchange_strong = op1_is_pointer && op1;
8843
8844 if (is_atomic_compare_exchange_strong)
Bill Hollings8f6df772017-05-19 18:14:08 -04008845 {
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008846 assert(strcmp(op, "atomic_compare_exchange_weak_explicit") == 0);
8847 assert(op2);
8848 assert(has_mem_order_2);
8849 exp += ", &";
8850 exp += to_name(result_id);
8851 exp += ", ";
8852 exp += to_expression(op2);
8853 exp += ", ";
8854 exp += get_memory_order(mem_order_1);
8855 exp += ", ";
8856 exp += get_memory_order(mem_order_2);
8857 exp += ")";
8858
Bill Hollingsefbe7ca2019-04-05 21:28:57 -04008859 // MSL only supports the weak atomic compare exchange, so emit a CAS loop here.
8860 // The MSL function returns false if the atomic write fails OR the comparison test fails,
8861 // so we must validate that it wasn't the comparison test that failed before continuing
8862 // the CAS loop, otherwise it will loop infinitely, with the comparison test always failing.
8863 // The function updates the comparitor value from the memory value, so the additional
8864 // comparison test evaluates the memory value against the expected value.
Hans-Kristian Arntzenc3e8e722019-07-26 11:16:43 +02008865 emit_uninitialized_temporary_expression(result_type, result_id);
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008866 statement("do");
8867 begin_scope();
8868 statement(to_name(result_id), " = ", to_expression(op1), ";");
Bill Hollingsefbe7ca2019-04-05 21:28:57 -04008869 end_scope_decl(join("while (!", exp, " && ", to_name(result_id), " == ", to_enclosed_expression(op1), ")"));
Bill Hollings8f6df772017-05-19 18:14:08 -04008870 }
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008871 else
8872 {
8873 assert(strcmp(op, "atomic_compare_exchange_weak_explicit") != 0);
8874 if (op1)
Chip Davis41eb5c42018-09-10 14:47:35 -05008875 {
Chip Davis06edf802018-09-13 08:56:23 -05008876 if (op1_is_literal)
Chip Davis41eb5c42018-09-10 14:47:35 -05008877 exp += join(", ", op1);
8878 else
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01008879 exp += ", " + bitcast_expression(expected_type, op1);
Chip Davis41eb5c42018-09-10 14:47:35 -05008880 }
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008881 if (op2)
8882 exp += ", " + to_expression(op2);
Bill Hollings8f6df772017-05-19 18:14:08 -04008883
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008884 exp += string(", ") + get_memory_order(mem_order_1);
8885 if (has_mem_order_2)
8886 exp += string(", ") + get_memory_order(mem_order_2);
Bill Hollings8f6df772017-05-19 18:14:08 -04008887
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008888 exp += ")";
Hans-Kristian Arntzen9b7140e2020-04-27 12:09:59 +02008889
Hans-Kristian Arntzenfce88702022-01-17 15:29:13 +01008890 if (expected_type != type.basetype)
8891 exp = bitcast_expression(type, expected_type, exp);
8892
Hans-Kristian Arntzen9b7140e2020-04-27 12:09:59 +02008893 if (strcmp(op, "atomic_store_explicit") != 0)
8894 emit_op(result_type, result_id, exp, false);
8895 else
8896 statement(exp, ";");
Hans-Kristian Arntzen26b887e2018-05-15 16:03:20 +02008897 }
Bill Hollings8f6df772017-05-19 18:14:08 -04008898
8899 flush_all_atomic_capable_variables();
8900}
8901
8902// Metal only supports relaxed memory order for now
8903const char *CompilerMSL::get_memory_order(uint32_t)
8904{
8905 return "memory_order_relaxed";
8906}
8907
Bill Hollings40141ff2021-09-22 18:58:31 -04008908// Override for MSL-specific extension syntax instructions.
8909// In some cases, deliberately select either the fast or precise versions of the MSL functions to match Vulkan math precision results.
Bill Hollingsf5f91042016-10-27 18:47:17 -04008910void CompilerMSL::emit_glsl_op(uint32_t result_type, uint32_t id, uint32_t eop, const uint32_t *args, uint32_t count)
8911{
Hans-Kristian Arntzeneeb3f242019-03-27 11:53:47 +01008912 auto op = static_cast<GLSLstd450>(eop);
8913
8914 // If we need to do implicit bitcasts, make sure we do it with the correct type.
8915 uint32_t integer_width = get_integer_width_for_glsl_instruction(op, args, count);
8916 auto int_type = to_signed_basetype(integer_width);
8917 auto uint_type = to_unsigned_basetype(integer_width);
Bill Hollingsf5f91042016-10-27 18:47:17 -04008918
8919 switch (op)
8920 {
Bill Hollings40141ff2021-09-22 18:58:31 -04008921 case GLSLstd450Sinh:
8922 emit_unary_func_op(result_type, id, args[0], "fast::sinh");
8923 break;
8924 case GLSLstd450Cosh:
8925 emit_unary_func_op(result_type, id, args[0], "fast::cosh");
8926 break;
8927 case GLSLstd450Tanh:
8928 emit_unary_func_op(result_type, id, args[0], "precise::tanh");
8929 break;
Bill Hollingsf5f91042016-10-27 18:47:17 -04008930 case GLSLstd450Atan2:
Bill Hollings40141ff2021-09-22 18:58:31 -04008931 emit_binary_func_op(result_type, id, args[0], args[1], "precise::atan2");
Bill Hollingsf5f91042016-10-27 18:47:17 -04008932 break;
Bill Hollings8f6df772017-05-19 18:14:08 -04008933 case GLSLstd450InverseSqrt:
8934 emit_unary_func_op(result_type, id, args[0], "rsqrt");
8935 break;
8936 case GLSLstd450RoundEven:
8937 emit_unary_func_op(result_type, id, args[0], "rint");
8938 break;
8939
Hans-Kristian Arntzen932ee0e2019-07-12 10:57:56 +02008940 case GLSLstd450FindILsb:
8941 {
8942 // In this template version of findLSB, we return T.
8943 auto basetype = expression_type(args[0]).basetype;
8944 emit_unary_func_op_cast(result_type, id, args[0], "spvFindLSB", basetype, basetype);
8945 break;
8946 }
8947
Bill Hollings8f6df772017-05-19 18:14:08 -04008948 case GLSLstd450FindSMsb:
Hans-Kristian Arntzen932ee0e2019-07-12 10:57:56 +02008949 emit_unary_func_op_cast(result_type, id, args[0], "spvFindSMSB", int_type, int_type);
Bill Hollings8f6df772017-05-19 18:14:08 -04008950 break;
Hans-Kristian Arntzeneeb3f242019-03-27 11:53:47 +01008951
Bill Hollings8f6df772017-05-19 18:14:08 -04008952 case GLSLstd450FindUMsb:
Hans-Kristian Arntzen932ee0e2019-07-12 10:57:56 +02008953 emit_unary_func_op_cast(result_type, id, args[0], "spvFindUMSB", uint_type, uint_type);
Bill Hollings8f6df772017-05-19 18:14:08 -04008954 break;
8955
8956 case GLSLstd450PackSnorm4x8:
8957 emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm4x8");
8958 break;
8959 case GLSLstd450PackUnorm4x8:
8960 emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm4x8");
8961 break;
8962 case GLSLstd450PackSnorm2x16:
8963 emit_unary_func_op(result_type, id, args[0], "pack_float_to_snorm2x16");
8964 break;
8965 case GLSLstd450PackUnorm2x16:
8966 emit_unary_func_op(result_type, id, args[0], "pack_float_to_unorm2x16");
8967 break;
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008968
Bill Hollings8f6df772017-05-19 18:14:08 -04008969 case GLSLstd450PackHalf2x16:
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008970 {
8971 auto expr = join("as_type<uint>(half2(", to_expression(args[0]), "))");
8972 emit_op(result_type, id, expr, should_forward(args[0]));
8973 inherit_expression_dependencies(id, args[0]);
Bill Hollings8f6df772017-05-19 18:14:08 -04008974 break;
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008975 }
Bill Hollings8f6df772017-05-19 18:14:08 -04008976
8977 case GLSLstd450UnpackSnorm4x8:
8978 emit_unary_func_op(result_type, id, args[0], "unpack_snorm4x8_to_float");
8979 break;
8980 case GLSLstd450UnpackUnorm4x8:
8981 emit_unary_func_op(result_type, id, args[0], "unpack_unorm4x8_to_float");
8982 break;
8983 case GLSLstd450UnpackSnorm2x16:
8984 emit_unary_func_op(result_type, id, args[0], "unpack_snorm2x16_to_float");
8985 break;
8986 case GLSLstd450UnpackUnorm2x16:
8987 emit_unary_func_op(result_type, id, args[0], "unpack_unorm2x16_to_float");
8988 break;
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008989
Bill Hollings8f6df772017-05-19 18:14:08 -04008990 case GLSLstd450UnpackHalf2x16:
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008991 {
8992 auto expr = join("float2(as_type<half2>(", to_expression(args[0]), "))");
8993 emit_op(result_type, id, expr, should_forward(args[0]));
8994 inherit_expression_dependencies(id, args[0]);
Bill Hollings8f6df772017-05-19 18:14:08 -04008995 break;
Hans-Kristian Arntzen4979d102018-03-12 17:51:14 +01008996 }
Bill Hollings8f6df772017-05-19 18:14:08 -04008997
8998 case GLSLstd450PackDouble2x32:
8999 emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450PackDouble2x32"); // Currently unsupported
9000 break;
9001 case GLSLstd450UnpackDouble2x32:
9002 emit_unary_func_op(result_type, id, args[0], "unsupported_GLSLstd450UnpackDouble2x32"); // Currently unsupported
9003 break;
9004
9005 case GLSLstd450MatrixInverse:
9006 {
9007 auto &mat_type = get<SPIRType>(result_type);
9008 switch (mat_type.columns)
9009 {
9010 case 2:
9011 emit_unary_func_op(result_type, id, args[0], "spvInverse2x2");
9012 break;
9013 case 3:
9014 emit_unary_func_op(result_type, id, args[0], "spvInverse3x3");
9015 break;
9016 case 4:
9017 emit_unary_func_op(result_type, id, args[0], "spvInverse4x4");
9018 break;
9019 default:
9020 break;
9021 }
9022 break;
9023 }
9024
Chip Davis27af7162018-08-31 18:15:07 -05009025 case GLSLstd450FMin:
9026 // If the result type isn't float, don't bother calling the specific
9027 // precise::/fast:: version. Metal doesn't have those for half and
9028 // double types.
9029 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9030 emit_binary_func_op(result_type, id, args[0], args[1], "min");
9031 else
9032 emit_binary_func_op(result_type, id, args[0], args[1], "fast::min");
9033 break;
9034
9035 case GLSLstd450FMax:
9036 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9037 emit_binary_func_op(result_type, id, args[0], args[1], "max");
9038 else
9039 emit_binary_func_op(result_type, id, args[0], args[1], "fast::max");
9040 break;
9041
9042 case GLSLstd450FClamp:
9043 // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
9044 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9045 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
9046 else
9047 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "fast::clamp");
9048 break;
9049
9050 case GLSLstd450NMin:
9051 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9052 emit_binary_func_op(result_type, id, args[0], args[1], "min");
9053 else
9054 emit_binary_func_op(result_type, id, args[0], args[1], "precise::min");
9055 break;
9056
9057 case GLSLstd450NMax:
9058 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9059 emit_binary_func_op(result_type, id, args[0], args[1], "max");
9060 else
9061 emit_binary_func_op(result_type, id, args[0], args[1], "precise::max");
9062 break;
9063
9064 case GLSLstd450NClamp:
9065 // TODO: If args[1] is 0 and args[2] is 1, emit a saturate() call.
9066 if (get<SPIRType>(result_type).basetype != SPIRType::Float)
9067 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "clamp");
9068 else
9069 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "precise::clamp");
9070 break;
9071
Chip Davisaca9b682020-11-02 20:56:46 -06009072 case GLSLstd450InterpolateAtCentroid:
9073 {
9074 // We can't just emit the expression normally, because the qualified name contains a call to the default
9075 // interpolate method, or refers to a local variable. We saved the interface index we need; use it to construct
9076 // the base for the method call.
9077 uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
9078 string component;
9079 if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
9080 {
9081 uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
9082 auto *c = maybe_get<SPIRConstant>(index_expr);
9083 if (!c || c->specialization)
9084 component = join("[", to_expression(index_expr), "]");
9085 else
9086 component = join(".", index_to_swizzle(c->scalar()));
9087 }
9088 emit_op(result_type, id,
9089 join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
Hans-Kristian Arntzen6fc2a052020-11-08 13:59:52 +01009090 ".interpolate_at_centroid()", component),
9091 should_forward(args[0]));
Chip Davisaca9b682020-11-02 20:56:46 -06009092 break;
9093 }
9094
9095 case GLSLstd450InterpolateAtSample:
9096 {
9097 uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
9098 string component;
9099 if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
9100 {
9101 uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
9102 auto *c = maybe_get<SPIRConstant>(index_expr);
9103 if (!c || c->specialization)
9104 component = join("[", to_expression(index_expr), "]");
9105 else
9106 component = join(".", index_to_swizzle(c->scalar()));
9107 }
9108 emit_op(result_type, id,
9109 join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
9110 ".interpolate_at_sample(", to_expression(args[1]), ")", component),
9111 should_forward(args[0]) && should_forward(args[1]));
9112 break;
9113 }
9114
9115 case GLSLstd450InterpolateAtOffset:
9116 {
9117 uint32_t interface_index = get_extended_decoration(args[0], SPIRVCrossDecorationInterfaceMemberIndex);
9118 string component;
9119 if (has_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr))
9120 {
9121 uint32_t index_expr = get_extended_decoration(args[0], SPIRVCrossDecorationInterpolantComponentExpr);
9122 auto *c = maybe_get<SPIRConstant>(index_expr);
9123 if (!c || c->specialization)
9124 component = join("[", to_expression(index_expr), "]");
9125 else
9126 component = join(".", index_to_swizzle(c->scalar()));
9127 }
9128 // Like Direct3D, Metal puts the (0, 0) at the upper-left corner, not the center as SPIR-V and GLSL do.
9129 // Offset the offset by (1/2 - 1/16), or 0.4375, to compensate for this.
9130 // It has to be (1/2 - 1/16) and not 1/2, or several CTS tests subtly break on Intel.
9131 emit_op(result_type, id,
9132 join(to_name(stage_in_var_id), ".", to_member_name(get_stage_in_struct_type(), interface_index),
9133 ".interpolate_at_offset(", to_expression(args[1]), " + 0.4375)", component),
9134 should_forward(args[0]) && should_forward(args[1]));
9135 break;
9136 }
Bill Hollingsf5f91042016-10-27 18:47:17 -04009137
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009138 case GLSLstd450Distance:
9139 // MSL does not support scalar versions here.
9140 if (expression_type(args[0]).vecsize == 1)
9141 {
9142 // Equivalent to length(a - b) -> abs(a - b).
9143 emit_op(result_type, id,
Le Hoang Quyenab8eb702020-08-13 16:57:13 +08009144 join("abs(", to_enclosed_unpacked_expression(args[0]), " - ",
9145 to_enclosed_unpacked_expression(args[1]), ")"),
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009146 should_forward(args[0]) && should_forward(args[1]));
9147 inherit_expression_dependencies(id, args[0]);
9148 inherit_expression_dependencies(id, args[1]);
9149 }
9150 else
9151 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9152 break;
9153
9154 case GLSLstd450Length:
Bill Hollings40141ff2021-09-22 18:58:31 -04009155 // MSL does not support scalar versions, so use abs().
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009156 if (expression_type(args[0]).vecsize == 1)
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009157 emit_unary_func_op(result_type, id, args[0], "abs");
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009158 else
9159 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9160 break;
9161
9162 case GLSLstd450Normalize:
9163 // MSL does not support scalar versions here.
Bill Hollings40141ff2021-09-22 18:58:31 -04009164 // Returns -1 or 1 for valid input, sign() does the job.
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009165 if (expression_type(args[0]).vecsize == 1)
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009166 emit_unary_func_op(result_type, id, args[0], "sign");
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009167 else
Bill Hollings40141ff2021-09-22 18:58:31 -04009168 emit_unary_func_op(result_type, id, args[0], "fast::normalize");
Hans-Kristian Arntzenff874192019-06-28 11:19:19 +02009169 break;
9170
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +02009171 case GLSLstd450Reflect:
9172 if (get<SPIRType>(result_type).vecsize == 1)
9173 emit_binary_func_op(result_type, id, args[0], args[1], "spvReflect");
9174 else
9175 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9176 break;
9177
9178 case GLSLstd450Refract:
9179 if (get<SPIRType>(result_type).vecsize == 1)
9180 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvRefract");
9181 else
9182 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9183 break;
9184
Hans-Kristian Arntzenc7eda1b2019-07-17 11:24:31 +02009185 case GLSLstd450FaceForward:
9186 if (get<SPIRType>(result_type).vecsize == 1)
9187 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "spvFaceForward");
9188 else
9189 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9190 break;
9191
Hans-Kristian Arntzenabb345d2019-07-26 11:02:38 +02009192 case GLSLstd450Modf:
9193 case GLSLstd450Frexp:
9194 {
9195 // Special case. If the variable is a scalar access chain, we cannot use it directly. We have to emit a temporary.
Hans-Kristian Arntzene40d19b2021-11-07 10:49:26 +01009196 // Another special case is if the variable is in a storage class which is not thread.
Hans-Kristian Arntzenabb345d2019-07-26 11:02:38 +02009197 auto *ptr = maybe_get<SPIRExpression>(args[1]);
Hans-Kristian Arntzene40d19b2021-11-07 10:49:26 +01009198 auto &type = expression_type(args[1]);
9199
9200 bool is_thread_storage = storage_class_array_is_thread(type.storage);
9201 if (type.storage == StorageClassOutput && capture_output_to_buffer)
9202 is_thread_storage = false;
9203
9204 if (!is_thread_storage ||
9205 (ptr && ptr->access_chain && is_scalar(expression_type(args[1]))))
Hans-Kristian Arntzenabb345d2019-07-26 11:02:38 +02009206 {
9207 register_call_out_argument(args[1]);
9208 forced_temporaries.insert(id);
9209
9210 // Need to create temporaries and copy over to access chain after.
9211 // We cannot directly take the reference of a vector swizzle in MSL, even if it's scalar ...
9212 uint32_t &tmp_id = extra_sub_expressions[id];
9213 if (!tmp_id)
9214 tmp_id = ir.increase_bound_by(1);
9215
Hans-Kristian Arntzene40d19b2021-11-07 10:49:26 +01009216 uint32_t tmp_type_id = get_pointee_type_id(expression_type_id(args[1]));
Hans-Kristian Arntzenabb345d2019-07-26 11:02:38 +02009217 emit_uninitialized_temporary_expression(tmp_type_id, tmp_id);
9218 emit_binary_func_op(result_type, id, args[0], tmp_id, eop == GLSLstd450Modf ? "modf" : "frexp");
9219 statement(to_expression(args[1]), " = ", to_expression(tmp_id), ";");
9220 }
9221 else
9222 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9223 break;
9224 }
9225
Bill Hollingsf5f91042016-10-27 18:47:17 -04009226 default:
9227 CompilerGLSL::emit_glsl_op(result_type, id, eop, args, count);
9228 break;
9229 }
9230}
9231
Chip Davisca91fcf2019-07-11 11:49:34 -05009232void CompilerMSL::emit_spv_amd_shader_trinary_minmax_op(uint32_t result_type, uint32_t id, uint32_t eop,
9233 const uint32_t *args, uint32_t count)
9234{
9235 enum AMDShaderTrinaryMinMax
9236 {
9237 FMin3AMD = 1,
9238 UMin3AMD = 2,
9239 SMin3AMD = 3,
9240 FMax3AMD = 4,
9241 UMax3AMD = 5,
9242 SMax3AMD = 6,
9243 FMid3AMD = 7,
9244 UMid3AMD = 8,
9245 SMid3AMD = 9
9246 };
9247
9248 if (!msl_options.supports_msl_version(2, 1))
9249 SPIRV_CROSS_THROW("Trinary min/max functions require MSL 2.1.");
9250
9251 auto op = static_cast<AMDShaderTrinaryMinMax>(eop);
9252
9253 switch (op)
9254 {
9255 case FMid3AMD:
9256 case UMid3AMD:
9257 case SMid3AMD:
9258 emit_trinary_func_op(result_type, id, args[0], args[1], args[2], "median3");
9259 break;
9260 default:
9261 CompilerGLSL::emit_spv_amd_shader_trinary_minmax_op(result_type, id, eop, args, count);
9262 break;
9263 }
9264}
9265
Bill Hollings103aabf2016-04-06 17:42:27 -04009266// Emit a structure declaration for the specified interface variable.
9267void CompilerMSL::emit_interface_block(uint32_t ib_var_id)
9268{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009269 if (ib_var_id)
9270 {
9271 auto &ib_var = get<SPIRVariable>(ib_var_id);
Chip Daviseb89c3a2019-02-03 23:58:46 -06009272 auto &ib_type = get_variable_data_type(ib_var);
Hans-Kristian Arntzenc635c352021-04-07 12:55:47 +02009273 //assert(ib_type.basetype == SPIRType::Struct && !ib_type.member_types.empty());
9274 assert(ib_type.basetype == SPIRType::Struct);
Hans-Kristian Arntzend3100602018-09-13 14:42:05 +02009275 emit_struct(ib_type);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009276 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009277}
9278
Bill Hollings103aabf2016-04-06 17:42:27 -04009279// Emits the declaration signature of the specified function.
9280// If this is the entry point function, Metal-specific return value and function arguments are added.
Hans-Kristian Arntzene8e58842018-03-12 13:09:25 +01009281void CompilerMSL::emit_function_prototype(SPIRFunction &func, const Bitset &)
Bill Hollings103aabf2016-04-06 17:42:27 -04009282{
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02009283 if (func.self != ir.default_entry_point)
Hans-Kristian Arntzena04bdcc2018-02-23 14:13:46 +01009284 add_function_overload(func);
9285
Hans-Kristian Arntzen6aa20072016-05-23 12:25:09 +02009286 local_variable_names = resource_names;
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04009287 string decl;
Bill Hollings103aabf2016-04-06 17:42:27 -04009288
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02009289 processing_entry_point = func.self == ir.default_entry_point;
Bill Hollings103aabf2016-04-06 17:42:27 -04009290
Lukas Hermanns50ac6862019-09-18 14:03:54 -04009291 // Metal helper functions must be static force-inline otherwise they will cause problems when linked together in a single Metallib.
Mark Satterthwaite8596bf52019-08-13 18:20:02 -04009292 if (!processing_entry_point)
Lukas Hermanns50ac6862019-09-18 14:03:54 -04009293 statement(force_inline);
Bill Hollings103aabf2016-04-06 17:42:27 -04009294
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009295 auto &type = get<SPIRType>(func.return_type);
Hans-Kristian Arntzen00ccd592018-02-05 12:37:41 +01009296
Hans-Kristian Arntzen20b28f72020-02-24 13:04:10 +01009297 if (!type.array.empty() && msl_options.force_native_arrays)
9298 {
9299 // We cannot return native arrays in MSL, so "return" through an out variable.
9300 decl += "void";
9301 }
9302 else
9303 {
9304 decl += func_type_decl(type);
9305 }
9306
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009307 decl += " ";
Bill Hollings1c180782017-11-05 21:34:42 -05009308 decl += to_name(func.self);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009309 decl += "(";
Bill Hollings103aabf2016-04-06 17:42:27 -04009310
Hans-Kristian Arntzen20b28f72020-02-24 13:04:10 +01009311 if (!type.array.empty() && msl_options.force_native_arrays)
9312 {
9313 // Fake arrays returns by writing to an out array instead.
9314 decl += "thread ";
9315 decl += type_to_glsl(type);
Hans-Kristian Arntzen6a614cc2020-11-23 15:42:27 +01009316 decl += " (&spvReturnValue)";
Hans-Kristian Arntzen20b28f72020-02-24 13:04:10 +01009317 decl += type_to_array_glsl(type);
9318 if (!func.arguments.empty())
9319 decl += ", ";
9320 }
9321
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009322 if (processing_entry_point)
9323 {
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +01009324 if (msl_options.argument_buffers)
9325 decl += entry_point_args_argument_buffer(!func.arguments.empty());
9326 else
9327 decl += entry_point_args_classic(!func.arguments.empty());
Bill Hollings103aabf2016-04-06 17:42:27 -04009328
Bill Hollings9b4defe2018-06-12 11:41:35 -04009329 // If entry point function has variables that require early declaration,
9330 // ensure they each have an empty initializer, creating one if needed.
9331 // This is done at this late stage because the initialization expression
9332 // is cleared after each compilation pass.
9333 for (auto var_id : vars_needing_early_declaration)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009334 {
Bill Hollings9b4defe2018-06-12 11:41:35 -04009335 auto &ed_var = get<SPIRVariable>(var_id);
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02009336 ID &initializer = ed_var.initializer;
Hans-Kristian Arntzen3e098792019-01-30 10:29:08 +01009337 if (!initializer)
9338 initializer = ir.increase_bound_by(1);
Bill Hollings9b4defe2018-06-12 11:41:35 -04009339
Hans-Kristian Arntzen3e098792019-01-30 10:29:08 +01009340 // Do not override proper initializers.
9341 if (ir.ids[initializer].get_type() == TypeNone || ir.ids[initializer].get_type() == TypeExpression)
9342 set<SPIRExpression>(ed_var.initializer, "{}", ed_var.basetype, true);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009343 }
9344 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009345
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009346 for (auto &arg : func.arguments)
9347 {
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +02009348 uint32_t name_id = arg.id;
Bill Hollings103aabf2016-04-06 17:42:27 -04009349
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009350 auto *var = maybe_get<SPIRVariable>(arg.id);
Bill Hollingsac00c602016-10-24 09:24:24 -04009351 if (var)
9352 {
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +02009353 // If we need to modify the name of the variable, make sure we modify the original variable.
9354 // Our alias is just a shadow variable.
9355 if (arg.alias_global_variable && var->basevariable)
9356 name_id = var->basevariable;
9357
Bill Hollingsac00c602016-10-24 09:24:24 -04009358 var->parameter = &arg; // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
Bill Hollingsac00c602016-10-24 09:24:24 -04009359 }
Bill Hollingsfe8b8602016-07-06 16:55:45 -04009360
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +02009361 add_local_variable_name(name_id);
9362
Bill Hollingsac00c602016-10-24 09:24:24 -04009363 decl += argument_decl(arg);
Bill Hollingsb321b832016-07-06 20:30:47 -04009364
Chip Davis39dce882019-08-02 15:11:19 -05009365 bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
9366
Bill Hollingsac00c602016-10-24 09:24:24 -04009367 auto &arg_type = get<SPIRType>(arg.type);
Chip Davis39dce882019-08-02 15:11:19 -05009368 if (arg_type.basetype == SPIRType::SampledImage && !is_dynamic_img_sampler)
9369 {
9370 // Manufacture automatic plane args for multiplanar texture
9371 uint32_t planes = 1;
9372 if (auto *constexpr_sampler = find_constexpr_sampler(name_id))
9373 if (constexpr_sampler->ycbcr_conversion_enable)
9374 planes = constexpr_sampler->planes;
9375 for (uint32_t i = 1; i < planes; i++)
9376 decl += join(", ", argument_decl(arg), plane_name_suffix, i);
9377
9378 // Manufacture automatic sampler arg for SampledImage texture
9379 if (arg_type.image.dim != DimBuffer)
Bill Hollingsb7b0e802020-10-29 18:50:42 -04009380 decl += join(", thread const ", sampler_type(arg_type, arg.id), " ", to_sampler_expression(arg.id));
Chip Davis39dce882019-08-02 15:11:19 -05009381 }
Bill Hollingsb321b832016-07-06 20:30:47 -04009382
Chip Davis664df222019-01-13 17:31:50 -06009383 // Manufacture automatic swizzle arg.
Chip Davis39dce882019-08-02 15:11:19 -05009384 if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(arg_type) &&
9385 !is_dynamic_img_sampler)
Hans-Kristian Arntzen97d39dc2019-05-09 11:25:45 +02009386 {
Hans-Kristian Arntzenad951732019-05-09 12:28:34 +02009387 bool arg_is_array = !arg_type.array.empty();
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +02009388 decl += join(", constant uint", arg_is_array ? "* " : "& ", to_swizzle_expression(arg.id));
9389 }
9390
9391 if (buffers_requiring_array_length.count(name_id))
9392 {
9393 bool arg_is_array = !arg_type.array.empty();
9394 decl += join(", constant uint", arg_is_array ? "* " : "& ", to_buffer_size_expression(name_id));
Hans-Kristian Arntzen97d39dc2019-05-09 11:25:45 +02009395 }
Chip Davis664df222019-01-13 17:31:50 -06009396
Bill Hollingsac00c602016-10-24 09:24:24 -04009397 if (&arg != &func.arguments.back())
9398 decl += ", ";
9399 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009400
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009401 decl += ")";
Bill Hollings2d0d3282017-01-20 11:33:59 -05009402 statement(decl);
Bill Hollings103aabf2016-04-06 17:42:27 -04009403}
9404
Chip Davis39dce882019-08-02 15:11:19 -05009405static bool needs_chroma_reconstruction(const MSLConstexprSampler *constexpr_sampler)
9406{
9407 // For now, only multiplanar images need explicit reconstruction. GBGR and BGRG images
9408 // use implicit reconstruction.
9409 return constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && constexpr_sampler->planes > 1;
9410}
9411
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009412// Returns the texture sampling function string for the specified image and sampling characteristics.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009413string CompilerMSL::to_function_name(const TextureFunctionNameArguments &args)
Bill Hollings103aabf2016-04-06 17:42:27 -04009414{
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009415 VariableID img = args.base.img;
Chip Davis39dce882019-08-02 15:11:19 -05009416 const MSLConstexprSampler *constexpr_sampler = nullptr;
9417 bool is_dynamic_img_sampler = false;
9418 if (auto *var = maybe_get_backing_variable(img))
9419 {
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02009420 constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
Chip Davis39dce882019-08-02 15:11:19 -05009421 is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
9422 }
9423
Chip Davis25833212018-09-19 20:36:33 -05009424 // Special-case gather. We have to alter the component being looked up
9425 // in the swizzle case.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009426 if (msl_options.swizzle_texture_samples && args.base.is_gather && !is_dynamic_img_sampler &&
Chip Davis39dce882019-08-02 15:11:19 -05009427 (!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable))
Chip Davis25833212018-09-19 20:36:33 -05009428 {
Bill Hollingsfd252b22021-11-08 15:59:45 -05009429 bool is_compare = comparison_ids.count(img);
9430 add_spv_func_and_recompile(is_compare ? SPVFuncImplGatherCompareSwizzle : SPVFuncImplGatherSwizzle);
9431 return is_compare ? "spvGatherCompareSwizzle" : "spvGatherSwizzle";
Chip Davis25833212018-09-19 20:36:33 -05009432 }
9433
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02009434 auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
9435
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009436 // Texture reference
Chip Davis39dce882019-08-02 15:11:19 -05009437 string fname;
9438 if (needs_chroma_reconstruction(constexpr_sampler) && !is_dynamic_img_sampler)
9439 {
9440 if (constexpr_sampler->planes != 2 && constexpr_sampler->planes != 3)
9441 SPIRV_CROSS_THROW("Unhandled number of color image planes!");
9442 // 444 images aren't downsampled, so we don't need to do linear filtering.
9443 if (constexpr_sampler->resolution == MSL_FORMAT_RESOLUTION_444 ||
9444 constexpr_sampler->chroma_filter == MSL_SAMPLER_FILTER_NEAREST)
9445 {
9446 if (constexpr_sampler->planes == 2)
9447 add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest2Plane);
9448 else
9449 add_spv_func_and_recompile(SPVFuncImplChromaReconstructNearest3Plane);
9450 fname = "spvChromaReconstructNearest";
9451 }
9452 else // Linear with a downsampled format
9453 {
9454 fname = "spvChromaReconstructLinear";
9455 switch (constexpr_sampler->resolution)
9456 {
9457 case MSL_FORMAT_RESOLUTION_444:
9458 assert(false);
9459 break; // not reached
9460 case MSL_FORMAT_RESOLUTION_422:
9461 switch (constexpr_sampler->x_chroma_offset)
9462 {
9463 case MSL_CHROMA_LOCATION_COSITED_EVEN:
9464 if (constexpr_sampler->planes == 2)
9465 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven2Plane);
9466 else
9467 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422CositedEven3Plane);
9468 fname += "422CositedEven";
9469 break;
9470 case MSL_CHROMA_LOCATION_MIDPOINT:
9471 if (constexpr_sampler->planes == 2)
9472 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint2Plane);
9473 else
9474 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear422Midpoint3Plane);
9475 fname += "422Midpoint";
9476 break;
9477 default:
9478 SPIRV_CROSS_THROW("Invalid chroma location.");
9479 }
9480 break;
9481 case MSL_FORMAT_RESOLUTION_420:
9482 fname += "420";
9483 switch (constexpr_sampler->x_chroma_offset)
9484 {
9485 case MSL_CHROMA_LOCATION_COSITED_EVEN:
9486 switch (constexpr_sampler->y_chroma_offset)
9487 {
9488 case MSL_CHROMA_LOCATION_COSITED_EVEN:
9489 if (constexpr_sampler->planes == 2)
9490 add_spv_func_and_recompile(
9491 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven2Plane);
9492 else
9493 add_spv_func_and_recompile(
9494 SPVFuncImplChromaReconstructLinear420XCositedEvenYCositedEven3Plane);
9495 fname += "XCositedEvenYCositedEven";
9496 break;
9497 case MSL_CHROMA_LOCATION_MIDPOINT:
9498 if (constexpr_sampler->planes == 2)
9499 add_spv_func_and_recompile(
9500 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint2Plane);
9501 else
9502 add_spv_func_and_recompile(
9503 SPVFuncImplChromaReconstructLinear420XCositedEvenYMidpoint3Plane);
9504 fname += "XCositedEvenYMidpoint";
9505 break;
9506 default:
9507 SPIRV_CROSS_THROW("Invalid Y chroma location.");
9508 }
9509 break;
9510 case MSL_CHROMA_LOCATION_MIDPOINT:
9511 switch (constexpr_sampler->y_chroma_offset)
9512 {
9513 case MSL_CHROMA_LOCATION_COSITED_EVEN:
9514 if (constexpr_sampler->planes == 2)
9515 add_spv_func_and_recompile(
9516 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven2Plane);
9517 else
9518 add_spv_func_and_recompile(
9519 SPVFuncImplChromaReconstructLinear420XMidpointYCositedEven3Plane);
9520 fname += "XMidpointYCositedEven";
9521 break;
9522 case MSL_CHROMA_LOCATION_MIDPOINT:
9523 if (constexpr_sampler->planes == 2)
9524 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint2Plane);
9525 else
9526 add_spv_func_and_recompile(SPVFuncImplChromaReconstructLinear420XMidpointYMidpoint3Plane);
9527 fname += "XMidpointYMidpoint";
9528 break;
9529 default:
9530 SPIRV_CROSS_THROW("Invalid Y chroma location.");
9531 }
9532 break;
9533 default:
9534 SPIRV_CROSS_THROW("Invalid X chroma location.");
9535 }
9536 break;
9537 default:
9538 SPIRV_CROSS_THROW("Invalid format resolution.");
9539 }
9540 }
9541 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009542 else
Chip Davis39dce882019-08-02 15:11:19 -05009543 {
9544 fname = to_expression(combined ? combined->image : img) + ".";
Bill Hollings103aabf2016-04-06 17:42:27 -04009545
Chip Davis39dce882019-08-02 15:11:19 -05009546 // Texture function and sampler
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009547 if (args.base.is_fetch)
Chip Davis39dce882019-08-02 15:11:19 -05009548 fname += "read";
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009549 else if (args.base.is_gather)
Chip Davis39dce882019-08-02 15:11:19 -05009550 fname += "gather";
9551 else
9552 fname += "sample";
9553
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009554 if (args.has_dref)
Chip Davis39dce882019-08-02 15:11:19 -05009555 fname += "_compare";
9556 }
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009557
9558 return fname;
9559}
9560
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009561string CompilerMSL::convert_to_f32(const string &expr, uint32_t components)
9562{
9563 SPIRType t;
9564 t.basetype = SPIRType::Float;
9565 t.vecsize = components;
9566 t.columns = 1;
9567 return join(type_to_glsl_constructor(t), "(", expr, ")");
9568}
9569
9570static inline bool sampling_type_needs_f32_conversion(const SPIRType &type)
9571{
9572 // Double is not supported to begin with, but doesn't hurt to check for completion.
9573 return type.basetype == SPIRType::Half || type.basetype == SPIRType::Double;
9574}
9575
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009576// Returns the function args for a texture sampling function for the specified image and sampling characteristics.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009577string CompilerMSL::to_function_args(const TextureFunctionArguments &args, bool *p_forward)
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009578{
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009579 VariableID img = args.base.img;
9580 auto &imgtype = *args.base.imgtype;
9581 uint32_t lod = args.lod;
9582 uint32_t grad_x = args.grad_x;
9583 uint32_t grad_y = args.grad_y;
9584 uint32_t bias = args.bias;
9585
Chip Davis39dce882019-08-02 15:11:19 -05009586 const MSLConstexprSampler *constexpr_sampler = nullptr;
9587 bool is_dynamic_img_sampler = false;
9588 if (auto *var = maybe_get_backing_variable(img))
Chip Davis25833212018-09-19 20:36:33 -05009589 {
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02009590 constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
Chip Davis39dce882019-08-02 15:11:19 -05009591 is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
9592 }
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +02009593
Chip Davis39dce882019-08-02 15:11:19 -05009594 string farg_str;
9595 bool forward = true;
9596
9597 if (!is_dynamic_img_sampler)
9598 {
9599 // Texture reference (for some cases)
9600 if (needs_chroma_reconstruction(constexpr_sampler))
9601 {
9602 // Multiplanar images need two or three textures.
9603 farg_str += to_expression(img);
9604 for (uint32_t i = 1; i < constexpr_sampler->planes; i++)
9605 farg_str += join(", ", to_expression(img), plane_name_suffix, i);
9606 }
9607 else if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009608 msl_options.swizzle_texture_samples && args.base.is_gather)
Chip Davis39dce882019-08-02 15:11:19 -05009609 {
9610 auto *combined = maybe_get<SPIRCombinedImageSampler>(img);
9611 farg_str += to_expression(combined ? combined->image : img);
9612 }
9613
9614 // Sampler reference
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009615 if (!args.base.is_fetch)
Chip Davis39dce882019-08-02 15:11:19 -05009616 {
9617 if (!farg_str.empty())
9618 farg_str += ", ";
9619 farg_str += to_sampler_expression(img);
9620 }
9621
9622 if ((!constexpr_sampler || !constexpr_sampler->ycbcr_conversion_enable) &&
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009623 msl_options.swizzle_texture_samples && args.base.is_gather)
Chip Davis39dce882019-08-02 15:11:19 -05009624 {
9625 // Add the swizzle constant from the swizzle buffer.
9626 farg_str += ", " + to_swizzle_expression(img);
9627 used_swizzle_buffer = true;
9628 }
9629
9630 // Swizzled gather puts the component before the other args, to allow template
9631 // deduction to work.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009632 if (args.component && msl_options.swizzle_texture_samples)
Chip Davis39dce882019-08-02 15:11:19 -05009633 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009634 forward = should_forward(args.component);
9635 farg_str += ", " + to_component_argument(args.component);
Chip Davis39dce882019-08-02 15:11:19 -05009636 }
Chip Davis25833212018-09-19 20:36:33 -05009637 }
9638
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009639 // Texture coordinates
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009640 forward = forward && should_forward(args.coord);
9641 auto coord_expr = to_enclosed_expression(args.coord);
9642 auto &coord_type = expression_type(args.coord);
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +01009643 bool coord_is_fp = type_is_floating_point(coord_type);
Bill Hollings561dc032017-04-25 16:32:16 -04009644 bool is_cube_fetch = false;
Bill Hollings6159a612017-02-09 12:14:30 -05009645
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009646 string tex_coords = coord_expr;
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009647 uint32_t alt_coord_component = 0;
Bill Hollings103aabf2016-04-06 17:42:27 -04009648
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009649 switch (imgtype.image.dim)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009650 {
Bill Hollings6159a612017-02-09 12:14:30 -05009651
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009652 case Dim1D:
Bill Hollings6159a612017-02-09 12:14:30 -05009653 if (coord_type.vecsize > 1)
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009654 tex_coords = enclose_expression(tex_coords) + ".x";
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009655
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009656 if (args.base.is_fetch)
Bill Hollings561dc032017-04-25 16:32:16 -04009657 tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009658 else if (sampling_type_needs_f32_conversion(coord_type))
9659 tex_coords = convert_to_f32(tex_coords, 1);
Bill Hollings561dc032017-04-25 16:32:16 -04009660
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009661 if (msl_options.texture_1D_as_2D)
9662 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009663 if (args.base.is_fetch)
Bill Hollings53d0dd62019-10-24 14:48:21 -04009664 tex_coords = "uint2(" + tex_coords + ", 0)";
9665 else
9666 tex_coords = "float2(" + tex_coords + ", 0.5)";
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009667 }
9668
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009669 alt_coord_component = 1;
Bill Hollings6159a612017-02-09 12:14:30 -05009670 break;
9671
9672 case DimBuffer:
9673 if (coord_type.vecsize > 1)
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009674 tex_coords = enclose_expression(tex_coords) + ".x";
Bill Hollings6159a612017-02-09 12:14:30 -05009675
Hans-Kristian Arntzenfc4f39b2019-04-23 12:17:21 +02009676 if (msl_options.texture_buffer_native)
9677 {
Hans-Kristian Arntzenc2715c32019-04-23 12:46:48 +02009678 tex_coords = "uint(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
Hans-Kristian Arntzenfc4f39b2019-04-23 12:17:21 +02009679 }
9680 else
9681 {
9682 // Metal texel buffer textures are 2D, so convert 1D coord to 2D.
Lukas Hermanns50ac6862019-09-18 14:03:54 -04009683 // Support for Metal 2.1's new texture_buffer type.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009684 if (args.base.is_fetch)
Mark Satterthwaite239e0472019-08-14 10:43:04 -04009685 {
9686 if (msl_options.texel_buffer_texture_width > 0)
9687 {
Lukas Hermanns50ac6862019-09-18 14:03:54 -04009688 tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
9689 }
Mark Satterthwaite239e0472019-08-14 10:43:04 -04009690 else
9691 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009692 tex_coords = "spvTexelBufferCoord(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ", " +
9693 to_expression(img) + ")";
Mark Satterthwaite239e0472019-08-14 10:43:04 -04009694 }
9695 }
Hans-Kristian Arntzenfc4f39b2019-04-23 12:17:21 +02009696 }
Bill Hollings561dc032017-04-25 16:32:16 -04009697
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009698 alt_coord_component = 1;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009699 break;
Bill Hollings103aabf2016-04-06 17:42:27 -04009700
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01009701 case DimSubpassData:
Hans-Kristian Arntzenb4338362019-10-24 11:48:29 +02009702 // If we're using Metal's native frame-buffer fetch API for subpass inputs,
9703 // this path will not be hit.
Chip Davis4cf840e2020-08-27 19:24:20 -05009704 tex_coords = "uint2(gl_FragCoord.xy)";
9705 alt_coord_component = 2;
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +01009706 break;
9707
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009708 case Dim2D:
Bill Hollings012cb252017-04-25 11:25:50 -04009709 if (coord_type.vecsize > 2)
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009710 tex_coords = enclose_expression(tex_coords) + ".xy";
Bill Hollingsef1f8602017-01-20 17:30:36 -05009711
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009712 if (args.base.is_fetch)
Bill Hollings561dc032017-04-25 16:32:16 -04009713 tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009714 else if (sampling_type_needs_f32_conversion(coord_type))
9715 tex_coords = convert_to_f32(tex_coords, 2);
Bill Hollings103aabf2016-04-06 17:42:27 -04009716
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009717 alt_coord_component = 2;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009718 break;
Bill Hollings103aabf2016-04-06 17:42:27 -04009719
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009720 case Dim3D:
Bill Hollings012cb252017-04-25 11:25:50 -04009721 if (coord_type.vecsize > 3)
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009722 tex_coords = enclose_expression(tex_coords) + ".xyz";
Bill Hollingsef1f8602017-01-20 17:30:36 -05009723
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009724 if (args.base.is_fetch)
Bill Hollings561dc032017-04-25 16:32:16 -04009725 tex_coords = "uint3(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009726 else if (sampling_type_needs_f32_conversion(coord_type))
9727 tex_coords = convert_to_f32(tex_coords, 3);
Bill Hollingsef1f8602017-01-20 17:30:36 -05009728
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009729 alt_coord_component = 3;
Bill Hollingsef1f8602017-01-20 17:30:36 -05009730 break;
9731
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009732 case DimCube:
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009733 if (args.base.is_fetch)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009734 {
Bill Hollings561dc032017-04-25 16:32:16 -04009735 is_cube_fetch = true;
9736 tex_coords += ".xy";
9737 tex_coords = "uint2(" + round_fp_tex_coords(tex_coords, coord_is_fp) + ")";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009738 }
9739 else
9740 {
Bill Hollings012cb252017-04-25 11:25:50 -04009741 if (coord_type.vecsize > 3)
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009742 tex_coords = enclose_expression(tex_coords) + ".xyz";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009743 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009744
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009745 if (sampling_type_needs_f32_conversion(coord_type))
9746 tex_coords = convert_to_f32(tex_coords, 3);
9747
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009748 alt_coord_component = 3;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009749 break;
Bill Hollings103aabf2016-04-06 17:42:27 -04009750
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009751 default:
9752 break;
9753 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009754
Chip Davis5845e002020-10-14 20:48:52 -05009755 if (args.base.is_fetch && (args.offset || args.coffset))
Hans-Kristian Arntzeneee290a2018-08-07 15:28:04 +02009756 {
Chip Davis5845e002020-10-14 20:48:52 -05009757 uint32_t offset_expr = args.offset ? args.offset : args.coffset;
Hans-Kristian Arntzeneee290a2018-08-07 15:28:04 +02009758 // Fetch offsets must be applied directly to the coordinate.
Chip Davis5845e002020-10-14 20:48:52 -05009759 forward = forward && should_forward(offset_expr);
9760 auto &type = expression_type(offset_expr);
9761 if (imgtype.image.dim == Dim1D && msl_options.texture_1D_as_2D)
9762 {
9763 if (type.basetype != SPIRType::UInt)
9764 tex_coords += join(" + uint2(", bitcast_expression(SPIRType::UInt, offset_expr), ", 0)");
9765 else
9766 tex_coords += join(" + uint2(", to_enclosed_expression(offset_expr), ", 0)");
9767 }
Hans-Kristian Arntzen981d7c12018-08-07 16:02:17 +02009768 else
Chip Davis5845e002020-10-14 20:48:52 -05009769 {
9770 if (type.basetype != SPIRType::UInt)
9771 tex_coords += " + " + bitcast_expression(SPIRType::UInt, offset_expr);
9772 else
9773 tex_coords += " + " + to_enclosed_expression(offset_expr);
9774 }
Hans-Kristian Arntzeneee290a2018-08-07 15:28:04 +02009775 }
9776
Bill Hollingsef1f8602017-01-20 17:30:36 -05009777 // If projection, use alt coord as divisor
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009778 if (args.base.is_proj)
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009779 {
9780 if (sampling_type_needs_f32_conversion(coord_type))
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009781 tex_coords += " / " + convert_to_f32(to_extract_component_expression(args.coord, alt_coord_component), 1);
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009782 else
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009783 tex_coords += " / " + to_extract_component_expression(args.coord, alt_coord_component);
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009784 }
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009785
Bill Hollingsef1f8602017-01-20 17:30:36 -05009786 if (!farg_str.empty())
9787 farg_str += ", ";
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009788
Lukas Hermannsf3a6d282019-09-27 15:49:54 -04009789 if (imgtype.image.dim == DimCube && imgtype.image.arrayed && msl_options.emulate_cube_array)
Hans-Kristian Arntzen04b149f2018-05-25 12:43:25 +02009790 {
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009791 farg_str += "spvCubemapTo2DArrayFace(" + tex_coords + ").xy";
Bill Hollingsef1f8602017-01-20 17:30:36 -05009792
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009793 if (is_cube_fetch)
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009794 farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ")";
Hans-Kristian Arntzen04b149f2018-05-25 12:43:25 +02009795 else
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02009796 farg_str +=
9797 ", uint(spvCubemapTo2DArrayFace(" + tex_coords + ").z) + (uint(" +
9798 round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
9799 ") * 6u)";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009800
Lukas Hermanns51be6012019-09-17 15:10:39 -04009801 add_spv_func_and_recompile(SPVFuncImplCubemapTo2DArrayFace);
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009802 }
9803 else
9804 {
9805 farg_str += tex_coords;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009806
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009807 // If fetch from cube, add face explicitly
9808 if (is_cube_fetch)
9809 {
9810 // Special case for cube arrays, face and layer are packed in one dimension.
9811 if (imgtype.image.arrayed)
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009812 farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") % 6u";
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009813 else
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009814 farg_str +=
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009815 ", uint(" + round_fp_tex_coords(to_extract_component_expression(args.coord, 2), coord_is_fp) + ")";
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009816 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009817
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009818 // If array, use alt coord
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009819 if (imgtype.image.arrayed)
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009820 {
9821 // Special case for cube arrays, face and layer are packed in one dimension.
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009822 if (imgtype.image.dim == DimCube && args.base.is_fetch)
Chip Davis4cf840e2020-08-27 19:24:20 -05009823 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009824 farg_str += ", uint(" + to_extract_component_expression(args.coord, 2) + ") / 6u";
Chip Davis4cf840e2020-08-27 19:24:20 -05009825 }
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009826 else
Chip Davis4cf840e2020-08-27 19:24:20 -05009827 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -04009828 farg_str +=
9829 ", uint(" +
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02009830 round_fp_tex_coords(to_extract_component_expression(args.coord, alt_coord_component), coord_is_fp) +
9831 ")";
Chip Davis4cf840e2020-08-27 19:24:20 -05009832 if (imgtype.image.dim == DimSubpassData)
9833 {
9834 if (msl_options.multiview)
9835 farg_str += " + gl_ViewIndex";
9836 else if (msl_options.arrayed_subpass_input)
9837 farg_str += " + gl_Layer";
9838 }
9839 }
9840 }
9841 else if (imgtype.image.dim == DimSubpassData)
9842 {
9843 if (msl_options.multiview)
9844 farg_str += ", gl_ViewIndex";
9845 else if (msl_options.arrayed_subpass_input)
9846 farg_str += ", gl_Layer";
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009847 }
Hans-Kristian Arntzen04b149f2018-05-25 12:43:25 +02009848 }
Bill Hollingsef1f8602017-01-20 17:30:36 -05009849
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009850 // Depth compare reference value
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009851 if (args.dref)
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009852 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009853 forward = forward && should_forward(args.dref);
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009854 farg_str += ", ";
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009855
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009856 auto &dref_type = expression_type(args.dref);
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009857
9858 string dref_expr;
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009859 if (args.base.is_proj)
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +02009860 dref_expr = join(to_enclosed_expression(args.dref), " / ",
9861 to_extract_component_expression(args.coord, alt_coord_component));
Hans-Kristian Arntzen18a4acc2019-01-28 09:39:45 +01009862 else
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009863 dref_expr = to_expression(args.dref);
Hans-Kristian Arntzenc76b99b2019-06-27 15:04:22 +02009864
9865 if (sampling_type_needs_f32_conversion(dref_type))
9866 dref_expr = convert_to_f32(dref_expr, 1);
9867
9868 farg_str += dref_expr;
Hans-Kristian Arntzen649ce3c2019-01-07 10:01:00 +01009869
9870 if (msl_options.is_macos() && (grad_x || grad_y))
9871 {
9872 // For sample compare, MSL does not support gradient2d for all targets (only iOS apparently according to docs).
9873 // However, the most common case here is to have a constant gradient of 0, as that is the only way to express
9874 // LOD == 0 in GLSL with sampler2DArrayShadow (cascaded shadow mapping).
9875 // We will detect a compile-time constant 0 value for gradient and promote that to level(0) on MSL.
9876 bool constant_zero_x = !grad_x || expression_is_constant_null(grad_x);
9877 bool constant_zero_y = !grad_y || expression_is_constant_null(grad_y);
9878 if (constant_zero_x && constant_zero_y)
9879 {
9880 lod = 0;
9881 grad_x = 0;
9882 grad_y = 0;
9883 farg_str += ", level(0)";
9884 }
Chip Davis547c29f2020-10-27 22:25:18 -05009885 else if (!msl_options.supports_msl_version(2, 3))
Hans-Kristian Arntzen649ce3c2019-01-07 10:01:00 +01009886 {
Hans-Kristian Arntzen5b876222019-01-07 10:01:28 +01009887 SPIRV_CROSS_THROW("Using non-constant 0.0 gradient() qualifier for sample_compare. This is not "
Chip Davis547c29f2020-10-27 22:25:18 -05009888 "supported on macOS prior to MSL 2.3.");
Hans-Kristian Arntzen649ce3c2019-01-07 10:01:00 +01009889 }
9890 }
9891
9892 if (msl_options.is_macos() && bias)
9893 {
9894 // Bias is not supported either on macOS with sample_compare.
9895 // Verify it is compile-time zero, and drop the argument.
9896 if (expression_is_constant_null(bias))
9897 {
9898 bias = 0;
9899 }
Chip Davis547c29f2020-10-27 22:25:18 -05009900 else if (!msl_options.supports_msl_version(2, 3))
Hans-Kristian Arntzen649ce3c2019-01-07 10:01:00 +01009901 {
Hans-Kristian Arntzen6fc2a052020-11-08 13:59:52 +01009902 SPIRV_CROSS_THROW("Using non-constant 0.0 bias() qualifier for sample_compare. This is not supported "
9903 "on macOS prior to MSL 2.3.");
Hans-Kristian Arntzen649ce3c2019-01-07 10:01:00 +01009904 }
9905 }
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009906 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009907
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009908 // LOD Options
Hans-Kristian Arntzen81eb72a2018-04-03 13:01:52 +02009909 // Metal does not support LOD for 1D textures.
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009910 if (bias && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009911 {
9912 forward = forward && should_forward(bias);
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009913 farg_str += ", bias(" + to_expression(bias) + ")";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009914 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009915
Hans-Kristian Arntzen81eb72a2018-04-03 13:01:52 +02009916 // Metal does not support LOD for 1D textures.
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009917 if (lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009918 {
9919 forward = forward && should_forward(lod);
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009920 if (args.base.is_fetch)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009921 {
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009922 farg_str += ", " + to_expression(lod);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009923 }
9924 else
9925 {
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009926 farg_str += ", level(" + to_expression(lod) + ")";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009927 }
9928 }
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009929 else if (args.base.is_fetch && !lod && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D) &&
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009930 imgtype.image.dim != DimBuffer && !imgtype.image.ms && imgtype.image.sampled != 2)
Hans-Kristian Arntzend93807a2018-04-30 10:53:21 +02009931 {
9932 // Lod argument is optional in OpImageFetch, but we require a LOD value, pick 0 as the default.
9933 // Check for sampled type as well, because is_fetch is also used for OpImageRead in MSL.
9934 farg_str += ", 0";
9935 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009936
Hans-Kristian Arntzen81eb72a2018-04-03 13:01:52 +02009937 // Metal does not support LOD for 1D textures.
Bill Hollings4b5c6c12019-10-24 12:31:20 -04009938 if ((grad_x || grad_y) && (imgtype.image.dim != Dim1D || msl_options.texture_1D_as_2D))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009939 {
9940 forward = forward && should_forward(grad_x);
9941 forward = forward && should_forward(grad_y);
9942 string grad_opt;
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009943 switch (imgtype.image.dim)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009944 {
Chip Davis5845e002020-10-14 20:48:52 -05009945 case Dim1D:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009946 case Dim2D:
9947 grad_opt = "2d";
9948 break;
9949 case Dim3D:
9950 grad_opt = "3d";
9951 break;
9952 case DimCube:
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -04009953 if (imgtype.image.arrayed && msl_options.emulate_cube_array)
9954 grad_opt = "2d";
9955 else
9956 grad_opt = "cube";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009957 break;
9958 default:
9959 grad_opt = "unsupported_gradient_dimension";
9960 break;
9961 }
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009962 farg_str += ", gradient" + grad_opt + "(" + to_expression(grad_x) + ", " + to_expression(grad_y) + ")";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009963 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009964
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009965 if (args.min_lod)
Hans-Kristian Arntzenf171d822019-06-11 11:10:16 +02009966 {
Chip Davis88e25e62020-11-14 01:57:11 -06009967 if (!msl_options.supports_msl_version(2, 2))
9968 SPIRV_CROSS_THROW("min_lod_clamp() is only supported in MSL 2.2+ and up.");
Hans-Kristian Arntzenf171d822019-06-11 11:10:16 +02009969
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009970 forward = forward && should_forward(args.min_lod);
9971 farg_str += ", min_lod_clamp(" + to_expression(args.min_lod) + ")";
Hans-Kristian Arntzenf171d822019-06-11 11:10:16 +02009972 }
9973
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009974 // Add offsets
9975 string offset_expr;
Chip Davis5845e002020-10-14 20:48:52 -05009976 const SPIRType *offset_type = nullptr;
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009977 if (args.coffset && !args.base.is_fetch)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009978 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009979 forward = forward && should_forward(args.coffset);
9980 offset_expr = to_expression(args.coffset);
Chip Davis5845e002020-10-14 20:48:52 -05009981 offset_type = &expression_type(args.coffset);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009982 }
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009983 else if (args.offset && !args.base.is_fetch)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009984 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +02009985 forward = forward && should_forward(args.offset);
9986 offset_expr = to_expression(args.offset);
Chip Davis5845e002020-10-14 20:48:52 -05009987 offset_type = &expression_type(args.offset);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009988 }
Bill Hollings103aabf2016-04-06 17:42:27 -04009989
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009990 if (!offset_expr.empty())
9991 {
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -05009992 switch (imgtype.image.dim)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02009993 {
Chip Davis5845e002020-10-14 20:48:52 -05009994 case Dim1D:
9995 if (!msl_options.texture_1D_as_2D)
9996 break;
9997 if (offset_type->vecsize > 1)
9998 offset_expr = enclose_expression(offset_expr) + ".x";
9999
10000 farg_str += join(", int2(", offset_expr, ", 0)");
10001 break;
10002
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010003 case Dim2D:
Chip Davis5845e002020-10-14 20:48:52 -050010004 if (offset_type->vecsize > 2)
Hans-Kristian Arntzen81eb72a2018-04-03 13:01:52 +020010005 offset_expr = enclose_expression(offset_expr) + ".xy";
Bill Hollings57213cb2018-04-30 16:30:29 -040010006
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010007 farg_str += ", " + offset_expr;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010008 break;
Bill Hollings103aabf2016-04-06 17:42:27 -040010009
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010010 case Dim3D:
Chip Davis5845e002020-10-14 20:48:52 -050010011 if (offset_type->vecsize > 3)
Hans-Kristian Arntzen81eb72a2018-04-03 13:01:52 +020010012 offset_expr = enclose_expression(offset_expr) + ".xyz";
Bill Hollings57213cb2018-04-30 16:30:29 -040010013
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010014 farg_str += ", " + offset_expr;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010015 break;
Bill Hollings103aabf2016-04-06 17:42:27 -040010016
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010017 default:
10018 break;
10019 }
10020 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010021
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +020010022 if (args.component)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010023 {
Bill Hollings57213cb2018-04-30 16:30:29 -040010024 // If 2D has gather component, ensure it also has an offset arg
10025 if (imgtype.image.dim == Dim2D && offset_expr.empty())
10026 farg_str += ", int2(0)";
10027
Chip Davis39dce882019-08-02 15:11:19 -050010028 if (!msl_options.swizzle_texture_samples || is_dynamic_img_sampler)
10029 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +020010030 forward = forward && should_forward(args.component);
Hans-Kristian Arntzenf65f2592020-10-26 10:15:48 +010010031
Hans-Kristian Arntzendb137622020-11-06 16:09:51 +010010032 uint32_t image_var = 0;
10033 if (const auto *combined = maybe_get<SPIRCombinedImageSampler>(img))
10034 {
10035 if (const auto *img_var = maybe_get_backing_variable(combined->image))
10036 image_var = img_var->self;
10037 }
10038 else if (const auto *var = maybe_get_backing_variable(img))
10039 {
10040 image_var = var->self;
10041 }
10042
Bill Hollingsfd252b22021-11-08 15:59:45 -050010043 if (image_var == 0 || !is_depth_image(expression_type(image_var), image_var))
Hans-Kristian Arntzendb137622020-11-06 16:09:51 +010010044 farg_str += ", " + to_component_argument(args.component);
Chip Davis39dce882019-08-02 15:11:19 -050010045 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010046 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010047
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +020010048 if (args.sample)
Bill Hollingsef1f8602017-01-20 17:30:36 -050010049 {
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +020010050 forward = forward && should_forward(args.sample);
Bill Hollingsef1f8602017-01-20 17:30:36 -050010051 farg_str += ", ";
Hans-Kristian Arntzencbe0cca2020-06-05 15:49:17 +020010052 farg_str += to_expression(args.sample);
Bill Hollingsef1f8602017-01-20 17:30:36 -050010053 }
10054
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010055 *p_forward = forward;
Bill Hollings103aabf2016-04-06 17:42:27 -040010056
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010057 return farg_str;
10058}
10059
Bill Hollings561dc032017-04-25 16:32:16 -040010060// If the texture coordinates are floating point, invokes MSL round() function to round them.
10061string CompilerMSL::round_fp_tex_coords(string tex_coords, bool coord_is_fp)
10062{
10063 return coord_is_fp ? ("round(" + tex_coords + ")") : tex_coords;
10064}
10065
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010066// Returns a string to use in an image sampling function argument.
10067// The ID must be a scalar constant.
10068string CompilerMSL::to_component_argument(uint32_t id)
10069{
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +020010070 uint32_t component_index = evaluate_constant_u32(id);
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010071 switch (component_index)
10072 {
10073 case 0:
10074 return "component::x";
10075 case 1:
10076 return "component::y";
10077 case 2:
10078 return "component::z";
10079 case 3:
10080 return "component::w";
10081
10082 default:
10083 SPIRV_CROSS_THROW("The value (" + to_string(component_index) + ") of OpConstant ID " + to_string(id) +
10084 " is not a valid Component index, which must be one of 0, 1, 2, or 3.");
Bill Hollingsa2b8a0e2016-12-28 18:36:42 -050010085 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010086}
10087
Bill Hollings5aafb282016-04-23 21:47:41 -040010088// Establish sampled image as expression object and assign the sampler to it.
10089void CompilerMSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
10090{
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +020010091 set<SPIRCombinedImageSampler>(result_id, result_type, image_id, samp_id);
Bill Hollings5aafb282016-04-23 21:47:41 -040010092}
10093
Hans-Kristian Arntzend573a952020-07-01 11:42:58 +020010094string CompilerMSL::to_texture_op(const Instruction &i, bool sparse, bool *forward,
10095 SmallVector<uint32_t> &inherited_expressions)
Chip Davis39dce882019-08-02 15:11:19 -050010096{
10097 auto *ops = stream(i);
10098 uint32_t result_type_id = ops[0];
10099 uint32_t img = ops[2];
10100 auto &result_type = get<SPIRType>(result_type_id);
10101 auto op = static_cast<Op>(i.op);
10102 bool is_gather = (op == OpImageGather || op == OpImageDrefGather);
10103
10104 // Bypass pointers because we need the real image struct
10105 auto &type = expression_type(img);
10106 auto &imgtype = get<SPIRType>(type.self);
10107
10108 const MSLConstexprSampler *constexpr_sampler = nullptr;
10109 bool is_dynamic_img_sampler = false;
10110 if (auto *var = maybe_get_backing_variable(img))
10111 {
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +020010112 constexpr_sampler = find_constexpr_sampler(var->basevariable ? var->basevariable : VariableID(var->self));
Chip Davis39dce882019-08-02 15:11:19 -050010113 is_dynamic_img_sampler = has_extended_decoration(var->self, SPIRVCrossDecorationDynamicImageSampler);
10114 }
10115
10116 string expr;
10117 if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
10118 {
10119 // If this needs sampler Y'CbCr conversion, we need to do some additional
10120 // processing.
10121 switch (constexpr_sampler->ycbcr_model)
10122 {
Alexander Meißner1f5875e2020-06-06 22:01:05 +020010123 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
10124 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
10125 // Default
10126 break;
Chip Davis39dce882019-08-02 15:11:19 -050010127 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
10128 add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT709);
10129 expr += "spvConvertYCbCrBT709(";
10130 break;
10131 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
10132 add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT601);
10133 expr += "spvConvertYCbCrBT601(";
10134 break;
10135 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
10136 add_spv_func_and_recompile(SPVFuncImplConvertYCbCrBT2020);
10137 expr += "spvConvertYCbCrBT2020(";
10138 break;
10139 default:
10140 SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
10141 }
10142
10143 if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
10144 {
10145 switch (constexpr_sampler->ycbcr_range)
10146 {
10147 case MSL_SAMPLER_YCBCR_RANGE_ITU_FULL:
10148 add_spv_func_and_recompile(SPVFuncImplExpandITUFullRange);
10149 expr += "spvExpandITUFullRange(";
10150 break;
10151 case MSL_SAMPLER_YCBCR_RANGE_ITU_NARROW:
10152 add_spv_func_and_recompile(SPVFuncImplExpandITUNarrowRange);
10153 expr += "spvExpandITUNarrowRange(";
10154 break;
10155 default:
10156 SPIRV_CROSS_THROW("Invalid Y'CbCr range.");
10157 }
10158 }
10159 }
10160 else if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
10161 !is_dynamic_img_sampler)
10162 {
10163 add_spv_func_and_recompile(SPVFuncImplTextureSwizzle);
10164 expr += "spvTextureSwizzle(";
10165 }
10166
Hans-Kristian Arntzen275974e2020-06-04 15:50:28 +020010167 string inner_expr = CompilerGLSL::to_texture_op(i, sparse, forward, inherited_expressions);
Chip Davis39dce882019-08-02 15:11:19 -050010168
10169 if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable && !is_dynamic_img_sampler)
10170 {
10171 if (!constexpr_sampler->swizzle_is_identity())
10172 {
10173 static const char swizzle_names[] = "rgba";
10174 if (!constexpr_sampler->swizzle_has_one_or_zero())
10175 {
10176 // If we can, do it inline.
10177 expr += inner_expr + ".";
10178 for (uint32_t c = 0; c < 4; c++)
10179 {
10180 switch (constexpr_sampler->swizzle[c])
10181 {
10182 case MSL_COMPONENT_SWIZZLE_IDENTITY:
10183 expr += swizzle_names[c];
10184 break;
10185 case MSL_COMPONENT_SWIZZLE_R:
10186 case MSL_COMPONENT_SWIZZLE_G:
10187 case MSL_COMPONENT_SWIZZLE_B:
10188 case MSL_COMPONENT_SWIZZLE_A:
10189 expr += swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
10190 break;
10191 default:
10192 SPIRV_CROSS_THROW("Invalid component swizzle.");
10193 }
10194 }
10195 }
10196 else
10197 {
10198 // Otherwise, we need to emit a temporary and swizzle that.
10199 uint32_t temp_id = ir.increase_bound_by(1);
10200 emit_op(result_type_id, temp_id, inner_expr, false);
10201 for (auto &inherit : inherited_expressions)
10202 inherit_expression_dependencies(temp_id, inherit);
10203 inherited_expressions.clear();
10204 inherited_expressions.push_back(temp_id);
10205
10206 switch (op)
10207 {
10208 case OpImageSampleDrefImplicitLod:
10209 case OpImageSampleImplicitLod:
10210 case OpImageSampleProjImplicitLod:
10211 case OpImageSampleProjDrefImplicitLod:
10212 register_control_dependent_expression(temp_id);
10213 break;
10214
10215 default:
10216 break;
10217 }
10218 expr += type_to_glsl(result_type) + "(";
10219 for (uint32_t c = 0; c < 4; c++)
10220 {
10221 switch (constexpr_sampler->swizzle[c])
10222 {
10223 case MSL_COMPONENT_SWIZZLE_IDENTITY:
10224 expr += to_expression(temp_id) + "." + swizzle_names[c];
10225 break;
10226 case MSL_COMPONENT_SWIZZLE_ZERO:
10227 expr += "0";
10228 break;
10229 case MSL_COMPONENT_SWIZZLE_ONE:
10230 expr += "1";
10231 break;
10232 case MSL_COMPONENT_SWIZZLE_R:
10233 case MSL_COMPONENT_SWIZZLE_G:
10234 case MSL_COMPONENT_SWIZZLE_B:
10235 case MSL_COMPONENT_SWIZZLE_A:
10236 expr += to_expression(temp_id) + "." +
10237 swizzle_names[constexpr_sampler->swizzle[c] - MSL_COMPONENT_SWIZZLE_R];
10238 break;
10239 default:
10240 SPIRV_CROSS_THROW("Invalid component swizzle.");
10241 }
10242 if (c < 3)
10243 expr += ", ";
10244 }
10245 expr += ")";
10246 }
10247 }
10248 else
10249 expr += inner_expr;
10250 if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY)
10251 {
10252 expr += join(", ", constexpr_sampler->bpc, ")");
10253 if (constexpr_sampler->ycbcr_model != MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY)
10254 expr += ")";
10255 }
10256 }
10257 else
10258 {
10259 expr += inner_expr;
10260 if (msl_options.swizzle_texture_samples && !is_gather && is_sampled_image_type(imgtype) &&
10261 !is_dynamic_img_sampler)
10262 {
10263 // Add the swizzle constant from the swizzle buffer.
10264 expr += ", " + to_swizzle_expression(img) + ")";
10265 used_swizzle_buffer = true;
10266 }
10267 }
10268
10269 return expr;
10270}
10271
10272static string create_swizzle(MSLComponentSwizzle swizzle)
10273{
10274 switch (swizzle)
10275 {
10276 case MSL_COMPONENT_SWIZZLE_IDENTITY:
10277 return "spvSwizzle::none";
10278 case MSL_COMPONENT_SWIZZLE_ZERO:
10279 return "spvSwizzle::zero";
10280 case MSL_COMPONENT_SWIZZLE_ONE:
10281 return "spvSwizzle::one";
10282 case MSL_COMPONENT_SWIZZLE_R:
10283 return "spvSwizzle::red";
10284 case MSL_COMPONENT_SWIZZLE_G:
10285 return "spvSwizzle::green";
10286 case MSL_COMPONENT_SWIZZLE_B:
10287 return "spvSwizzle::blue";
10288 case MSL_COMPONENT_SWIZZLE_A:
10289 return "spvSwizzle::alpha";
10290 default:
10291 SPIRV_CROSS_THROW("Invalid component swizzle.");
Chip Davis39dce882019-08-02 15:11:19 -050010292 }
10293}
10294
Bill Hollingsb321b832016-07-06 20:30:47 -040010295// Returns a string representation of the ID, usable as a function arg.
10296// Manufacture automatic sampler arg for SampledImage texture.
Chip Davis39dce882019-08-02 15:11:19 -050010297string CompilerMSL::to_func_call_arg(const SPIRFunction::Parameter &arg, uint32_t id)
Bill Hollingsb321b832016-07-06 20:30:47 -040010298{
Hans-Kristian Arntzen7ee04932019-01-14 10:08:35 +010010299 string arg_str;
10300
Chip Davis39dce882019-08-02 15:11:19 -050010301 auto &type = expression_type(id);
10302 bool is_dynamic_img_sampler = has_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
10303 // If the argument *itself* is a "dynamic" combined-image sampler, then we can just pass that around.
10304 bool arg_is_dynamic_img_sampler = has_extended_decoration(id, SPIRVCrossDecorationDynamicImageSampler);
10305 if (is_dynamic_img_sampler && !arg_is_dynamic_img_sampler)
10306 arg_str = join("spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">(");
10307
Hans-Kristian Arntzen30343f32020-02-24 13:22:52 +010010308 auto *c = maybe_get<SPIRConstant>(id);
10309 if (msl_options.force_native_arrays && c && !get<SPIRType>(c->constant_type).array.empty())
10310 {
10311 // If we are passing a constant array directly to a function for some reason,
10312 // the callee will expect an argument in thread const address space
10313 // (since we can only bind to arrays with references in MSL).
10314 // To resolve this, we must emit a copy in this address space.
10315 // This kind of code gen should be rare enough that performance is not a real concern.
10316 // Inline the SPIR-V to avoid this kind of suboptimal codegen.
10317 //
10318 // We risk calling this inside a continue block (invalid code),
10319 // so just create a thread local copy in the current function.
10320 arg_str = join("_", id, "_array_copy");
10321 auto &constants = current_function->constant_arrays_needed_on_stack;
10322 auto itr = find(begin(constants), end(constants), ID(id));
10323 if (itr == end(constants))
10324 {
10325 force_recompile();
10326 constants.push_back(id);
10327 }
10328 }
10329 else
10330 arg_str += CompilerGLSL::to_func_call_arg(arg, id);
Bill Hollingsb321b832016-07-06 20:30:47 -040010331
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040010332 // Need to check the base variable in case we need to apply a qualified alias.
10333 uint32_t var_id = 0;
10334 auto *var = maybe_get<SPIRVariable>(id);
10335 if (var)
10336 var_id = var->basevariable;
Bill Hollingsb321b832016-07-06 20:30:47 -040010337
Chip Davis39dce882019-08-02 15:11:19 -050010338 if (!arg_is_dynamic_img_sampler)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010339 {
Chip Davis39dce882019-08-02 15:11:19 -050010340 auto *constexpr_sampler = find_constexpr_sampler(var_id ? var_id : id);
10341 if (type.basetype == SPIRType::SampledImage)
10342 {
10343 // Manufacture automatic plane args for multiplanar texture
10344 uint32_t planes = 1;
10345 if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
10346 {
10347 planes = constexpr_sampler->planes;
10348 // If this parameter isn't aliasing a global, then we need to use
10349 // the special "dynamic image-sampler" class to pass it--and we need
10350 // to use it for *every* non-alias parameter, in case a combined
10351 // image-sampler with a Y'CbCr conversion is passed. Hopefully, this
10352 // pathological case is so rare that it should never be hit in practice.
10353 if (!arg.alias_global_variable)
10354 add_spv_func_and_recompile(SPVFuncImplDynamicImageSampler);
10355 }
10356 for (uint32_t i = 1; i < planes; i++)
10357 arg_str += join(", ", CompilerGLSL::to_func_call_arg(arg, id), plane_name_suffix, i);
10358 // Manufacture automatic sampler arg if the arg is a SampledImage texture.
10359 if (type.image.dim != DimBuffer)
10360 arg_str += ", " + to_sampler_expression(var_id ? var_id : id);
10361
10362 // Add sampler Y'CbCr conversion info if we have it
10363 if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
10364 {
10365 SmallVector<string> samp_args;
10366
10367 switch (constexpr_sampler->resolution)
10368 {
10369 case MSL_FORMAT_RESOLUTION_444:
10370 // Default
10371 break;
10372 case MSL_FORMAT_RESOLUTION_422:
10373 samp_args.push_back("spvFormatResolution::_422");
10374 break;
10375 case MSL_FORMAT_RESOLUTION_420:
10376 samp_args.push_back("spvFormatResolution::_420");
10377 break;
10378 default:
10379 SPIRV_CROSS_THROW("Invalid format resolution.");
10380 }
10381
10382 if (constexpr_sampler->chroma_filter != MSL_SAMPLER_FILTER_NEAREST)
10383 samp_args.push_back("spvChromaFilter::linear");
10384
10385 if (constexpr_sampler->x_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
10386 samp_args.push_back("spvXChromaLocation::midpoint");
10387 if (constexpr_sampler->y_chroma_offset != MSL_CHROMA_LOCATION_COSITED_EVEN)
10388 samp_args.push_back("spvYChromaLocation::midpoint");
10389 switch (constexpr_sampler->ycbcr_model)
10390 {
10391 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_RGB_IDENTITY:
10392 // Default
10393 break;
10394 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_IDENTITY:
10395 samp_args.push_back("spvYCbCrModelConversion::ycbcr_identity");
10396 break;
10397 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_709:
10398 samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_709");
10399 break;
10400 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_601:
10401 samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_601");
10402 break;
10403 case MSL_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_BT_2020:
10404 samp_args.push_back("spvYCbCrModelConversion::ycbcr_bt_2020");
10405 break;
10406 default:
10407 SPIRV_CROSS_THROW("Invalid Y'CbCr model conversion.");
10408 }
10409 if (constexpr_sampler->ycbcr_range != MSL_SAMPLER_YCBCR_RANGE_ITU_FULL)
10410 samp_args.push_back("spvYCbCrRange::itu_narrow");
10411 samp_args.push_back(join("spvComponentBits(", constexpr_sampler->bpc, ")"));
10412 arg_str += join(", spvYCbCrSampler(", merge(samp_args), ")");
10413 }
10414 }
10415
10416 if (is_dynamic_img_sampler && constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
10417 arg_str += join(", (uint(", create_swizzle(constexpr_sampler->swizzle[3]), ") << 24) | (uint(",
10418 create_swizzle(constexpr_sampler->swizzle[2]), ") << 16) | (uint(",
10419 create_swizzle(constexpr_sampler->swizzle[1]), ") << 8) | uint(",
10420 create_swizzle(constexpr_sampler->swizzle[0]), ")");
10421 else if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
10422 arg_str += ", " + to_swizzle_expression(var_id ? var_id : id);
10423
10424 if (buffers_requiring_array_length.count(var_id))
10425 arg_str += ", " + to_buffer_size_expression(var_id ? var_id : id);
10426
10427 if (is_dynamic_img_sampler)
10428 arg_str += ")";
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010429 }
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020010430
Lukas Hermanns50ac6862019-09-18 14:03:54 -040010431 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040010432 auto *backing_var = maybe_get_backing_variable(var_id);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020010433 if (backing_var && atomic_image_vars.count(backing_var->self))
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040010434 {
10435 arg_str += ", " + to_expression(var_id) + "_atomic";
10436 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040010437
Bill Hollingsac00c602016-10-24 09:24:24 -040010438 return arg_str;
Bill Hollingsb321b832016-07-06 20:30:47 -040010439}
10440
Bill Hollings5aafb282016-04-23 21:47:41 -040010441// If the ID represents a sampled image that has been assigned a sampler already,
10442// generate an expression for the sampler, otherwise generate a fake sampler name
10443// by appending a suffix to the expression constructed from the ID.
10444string CompilerMSL::to_sampler_expression(uint32_t id)
10445{
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +020010446 auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +020010447 auto expr = to_expression(combined ? combined->image : VariableID(id));
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020010448 auto index = expr.find_first_of('[');
Hans-Kristian Arntzena6972992018-10-05 09:49:57 +020010449
10450 uint32_t samp_id = 0;
10451 if (combined)
10452 samp_id = combined->sampler;
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020010453
10454 if (index == string::npos)
10455 return samp_id ? to_expression(samp_id) : expr + sampler_name_suffix;
10456 else
10457 {
10458 auto image_expr = expr.substr(0, index);
10459 auto array_expr = expr.substr(index);
10460 return samp_id ? to_expression(samp_id) : (image_expr + sampler_name_suffix + array_expr);
10461 }
Bill Hollings5aafb282016-04-23 21:47:41 -040010462}
10463
Chip Davis664df222019-01-13 17:31:50 -060010464string CompilerMSL::to_swizzle_expression(uint32_t id)
10465{
10466 auto *combined = maybe_get<SPIRCombinedImageSampler>(id);
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020010467
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +020010468 auto expr = to_expression(combined ? combined->image : VariableID(id));
Chip Davis664df222019-01-13 17:31:50 -060010469 auto index = expr.find_first_of('[');
10470
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020010471 // If an image is part of an argument buffer translate this to a legal identifier.
Chip Davis064ed442020-10-20 17:35:12 -050010472 string::size_type period = 0;
10473 while ((period = expr.find_first_of('.', period)) != string::npos && period < index)
10474 expr[period] = '_';
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020010475
Chip Davis664df222019-01-13 17:31:50 -060010476 if (index == string::npos)
10477 return expr + swizzle_name_suffix;
10478 else
10479 {
10480 auto image_expr = expr.substr(0, index);
10481 auto array_expr = expr.substr(index);
10482 return image_expr + swizzle_name_suffix + array_expr;
10483 }
10484}
10485
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020010486string CompilerMSL::to_buffer_size_expression(uint32_t id)
10487{
10488 auto expr = to_expression(id);
10489 auto index = expr.find_first_of('[');
10490
10491 // This is quite crude, but we need to translate the reference name (*spvDescriptorSetN.name) to
10492 // the pointer expression spvDescriptorSetN.name to make a reasonable expression here.
10493 // This only happens if we have argument buffers and we are using OpArrayLength on a lone SSBO in that set.
10494 if (expr.size() >= 3 && expr[0] == '(' && expr[1] == '*')
10495 expr = address_of_expression(expr);
10496
10497 // If a buffer is part of an argument buffer translate this to a legal identifier.
10498 for (auto &c : expr)
10499 if (c == '.')
10500 c = '_';
10501
10502 if (index == string::npos)
10503 return expr + buffer_size_name_suffix;
10504 else
10505 {
10506 auto buffer_expr = expr.substr(0, index);
10507 auto array_expr = expr.substr(index);
10508 return buffer_expr + buffer_size_name_suffix + array_expr;
10509 }
10510}
10511
Chip Davis6b798802019-02-15 17:21:38 -060010512// Checks whether the type is a Block all of whose members have DecorationPatch.
10513bool CompilerMSL::is_patch_block(const SPIRType &type)
10514{
10515 if (!has_decoration(type.self, DecorationBlock))
10516 return false;
10517
10518 for (uint32_t i = 0; i < type.member_types.size(); i++)
10519 {
10520 if (!has_member_decoration(type.self, i, DecorationPatch))
10521 return false;
10522 }
10523
10524 return true;
10525}
10526
Bill Hollings88905782018-01-04 16:33:45 -050010527// Checks whether the ID is a row_major matrix that requires conversion before use
10528bool CompilerMSL::is_non_native_row_major_matrix(uint32_t id)
10529{
Hans-Kristian Arntzen2172b192019-07-22 16:27:47 +020010530 auto *e = maybe_get<SPIRExpression>(id);
10531 if (e)
10532 return e->need_transpose;
10533 else
10534 return has_decoration(id, DecorationRowMajor);
Bill Hollings88905782018-01-04 16:33:45 -050010535}
10536
10537// Checks whether the member is a row_major matrix that requires conversion before use
10538bool CompilerMSL::member_is_non_native_row_major_matrix(const SPIRType &type, uint32_t index)
10539{
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +020010540 return has_member_decoration(type.self, index, DecorationRowMajor);
Bill Hollings88905782018-01-04 16:33:45 -050010541}
10542
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +020010543string CompilerMSL::convert_row_major_matrix(string exp_str, const SPIRType &exp_type, uint32_t physical_type_id,
10544 bool is_packed)
Bill Hollings88905782018-01-04 16:33:45 -050010545{
Hans-Kristian Arntzen249f8e52019-07-22 11:13:44 +020010546 if (!is_matrix(exp_type))
10547 {
10548 return CompilerGLSL::convert_row_major_matrix(move(exp_str), exp_type, physical_type_id, is_packed);
10549 }
10550 else
10551 {
10552 strip_enclosed_expression(exp_str);
10553 if (physical_type_id != 0 || is_packed)
10554 exp_str = unpack_expression_type(exp_str, exp_type, physical_type_id, is_packed, true);
10555 return join("transpose(", exp_str, ")");
10556 }
Bill Hollings88905782018-01-04 16:33:45 -050010557}
10558
Bill Hollings103aabf2016-04-06 17:42:27 -040010559// Called automatically at the end of the entry point function
10560void CompilerMSL::emit_fixup()
10561{
Hans-Kristian Arntzen5ea576e2020-09-28 14:09:39 +020010562 if (is_vertex_like_shader() && stage_out_var_id && !qual_pos_var_name.empty() && !capture_output_to_buffer)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010563 {
Hans-Kristian Arntzena803e5a2018-03-09 15:25:25 +010010564 if (options.vertex.fixup_clipspace)
Robert Konrada778c362017-01-15 16:39:03 +010010565 statement(qual_pos_var_name, ".z = (", qual_pos_var_name, ".z + ", qual_pos_var_name,
10566 ".w) * 0.5; // Adjust clip-space for Metal");
Bill Hollings103aabf2016-04-06 17:42:27 -040010567
Hans-Kristian Arntzena803e5a2018-03-09 15:25:25 +010010568 if (options.vertex.flip_vert_y)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010569 statement(qual_pos_var_name, ".y = -(", qual_pos_var_name, ".y);", " // Invert Y-axis for Metal");
10570 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010571}
10572
Chip Davisc51e5b72019-01-08 16:33:32 -060010573// Return a string defining a structure member, with padding and packing.
10574string CompilerMSL::to_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
10575 const string &qualifier)
Bill Hollings103aabf2016-04-06 17:42:27 -040010576{
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010577 if (member_is_remapped_physical_type(type, index))
10578 member_type_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID);
10579 auto &physical_type = get<SPIRType>(member_type_id);
Bill Hollings484931d2017-02-28 21:44:36 -050010580
Bill Hollings484931d2017-02-28 21:44:36 -050010581 // If this member is packed, mark it as so.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010582 string pack_pfx;
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +010010583
Lukas Hermanns50ac6862019-09-18 14:03:54 -040010584 // Allow Metal to use the array<T> template to make arrays a value type
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010585 uint32_t orig_id = 0;
10586 if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID))
10587 orig_id = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID);
10588
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +020010589 bool row_major = false;
10590 if (is_matrix(physical_type))
10591 row_major = has_member_decoration(type.self, index, DecorationRowMajor);
10592
10593 SPIRType row_major_physical_type;
10594 const SPIRType *declared_type = &physical_type;
10595
Hans-Kristian Arntzend1479f82019-10-24 12:22:30 +020010596 // If a struct is being declared with physical layout,
10597 // do not use array<T> wrappers.
10598 // This avoids a lot of complicated cases with packed vectors and matrices,
10599 // and generally we cannot copy full arrays in and out of buffers into Function
10600 // address space.
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020010601 // Array of resources should also be declared as builtin arrays.
Hans-Kristian Arntzend1479f82019-10-24 12:22:30 +020010602 if (has_member_decoration(type.self, index, DecorationOffset))
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010010603 is_using_builtin_array = true;
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020010604 else if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010010605 is_using_builtin_array = true;
Hans-Kristian Arntzend1479f82019-10-24 12:22:30 +020010606
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010607 if (member_is_packed_physical_type(type, index))
Bill Hollings607b0d62018-02-11 16:52:57 -050010608 {
Bill Hollings607b0d62018-02-11 16:52:57 -050010609 // If we're packing a matrix, output an appropriate typedef
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010610 if (physical_type.basetype == SPIRType::Struct)
Hans-Kristian Arntzen217eb5b2019-01-28 11:32:06 +010010611 {
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010612 SPIRV_CROSS_THROW("Cannot emit a packed struct currently.");
Hans-Kristian Arntzen217eb5b2019-01-28 11:32:06 +010010613 }
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010614 else if (is_matrix(physical_type))
Bill Hollings607b0d62018-02-11 16:52:57 -050010615 {
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010616 uint32_t rows = physical_type.vecsize;
10617 uint32_t cols = physical_type.columns;
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +010010618 pack_pfx = "packed_";
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +020010619 if (row_major)
Chip Davis28454fa2019-07-10 18:37:31 -050010620 {
10621 // These are stored transposed.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010622 rows = physical_type.columns;
10623 cols = physical_type.vecsize;
Chip Davis28454fa2019-07-10 18:37:31 -050010624 pack_pfx = "packed_rm_";
10625 }
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010626 string base_type = physical_type.width == 16 ? "half" : "float";
Bill Hollings607b0d62018-02-11 16:52:57 -050010627 string td_line = "typedef ";
Chip Davis28454fa2019-07-10 18:37:31 -050010628 td_line += "packed_" + base_type + to_string(rows);
Bill Hollings607b0d62018-02-11 16:52:57 -050010629 td_line += " " + pack_pfx;
Chip Davis28454fa2019-07-10 18:37:31 -050010630 // Use the actual matrix size here.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010631 td_line += base_type + to_string(physical_type.columns) + "x" + to_string(physical_type.vecsize);
Chip Davis28454fa2019-07-10 18:37:31 -050010632 td_line += "[" + to_string(cols) + "]";
Bill Hollings607b0d62018-02-11 16:52:57 -050010633 td_line += ";";
10634 add_typedef_line(td_line);
10635 }
Le Hoang Quyen9ddfe6d2020-05-06 00:39:56 +080010636 else if (!is_scalar(physical_type)) // scalar type is already packed.
Hans-Kristian Arntzen64ca1ec2019-01-16 16:16:39 +010010637 pack_pfx = "packed_";
Bill Hollings607b0d62018-02-11 16:52:57 -050010638 }
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +020010639 else if (row_major)
10640 {
10641 // Need to declare type with flipped vecsize/columns.
10642 row_major_physical_type = physical_type;
10643 swap(row_major_physical_type.vecsize, row_major_physical_type.columns);
10644 declared_type = &row_major_physical_type;
10645 }
Bill Hollings484931d2017-02-28 21:44:36 -050010646
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010010647 // Very specifically, image load-store in argument buffers are disallowed on MSL on iOS.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010648 if (msl_options.is_ios() && physical_type.basetype == SPIRType::Image && physical_type.image.sampled == 2)
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010010649 {
10650 if (!has_decoration(orig_id, DecorationNonWritable))
10651 SPIRV_CROSS_THROW("Writable images are not allowed in argument buffers on iOS.");
10652 }
10653
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010654 // Array information is baked into these types.
10655 string array_type;
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010656 if (physical_type.basetype != SPIRType::Image && physical_type.basetype != SPIRType::Sampler &&
10657 physical_type.basetype != SPIRType::SampledImage)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010658 {
Mark Satterthwaited50659a2019-08-13 18:18:48 -040010659 BuiltIn builtin = BuiltInMax;
Hans-Kristian Arntzenab9200f2021-01-06 10:33:17 +010010660
10661 // Special handling. In [[stage_out]] or [[stage_in]] blocks,
10662 // we need flat arrays, but if we're somehow declaring gl_PerVertex for constant array reasons, we want
10663 // template array types to be declared.
10664 bool is_ib_in_out =
Hans-Kristian Arntzenc1edd352021-04-16 11:45:50 +020010665 ((stage_out_var_id && get_stage_out_struct_type().self == type.self &&
10666 variable_storage_requires_stage_io(StorageClassOutput)) ||
10667 (stage_in_var_id && get_stage_in_struct_type().self == type.self &&
10668 variable_storage_requires_stage_io(StorageClassInput)));
Hans-Kristian Arntzenab9200f2021-01-06 10:33:17 +010010669 if (is_ib_in_out && is_member_builtin(type, index, &builtin))
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010010670 is_using_builtin_array = true;
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020010671 array_type = type_to_array_glsl(physical_type);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010672 }
10673
Hans-Kristian Arntzend1479f82019-10-24 12:22:30 +020010674 auto result = join(pack_pfx, type_to_glsl(*declared_type, orig_id), " ", qualifier, to_member_name(type, index),
10675 member_attribute_qualifier(type, index), array_type, ";");
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040010676
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010010677 is_using_builtin_array = false;
Mark Satterthwaited50659a2019-08-13 18:18:48 -040010678 return result;
Chip Davisc51e5b72019-01-08 16:33:32 -060010679}
10680
10681// Emit a structure member, padding and packing to maintain the correct memeber alignments.
10682void CompilerMSL::emit_struct_member(const SPIRType &type, uint32_t member_type_id, uint32_t index,
10683 const string &qualifier, uint32_t)
10684{
Hans-Kristian Arntzendd7ebaf2019-07-18 17:05:28 +020010685 // If this member requires padding to maintain its declared offset, emit a dummy padding member before it.
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020010686 if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget))
Hans-Kristian Arntzendd7ebaf2019-07-18 17:05:28 +020010687 {
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020010688 uint32_t pad_len = get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPaddingTarget);
10689 statement("char _m", index, "_pad", "[", pad_len, "];");
Hans-Kristian Arntzendd7ebaf2019-07-18 17:05:28 +020010690 }
10691
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040010692 // Handle HLSL-style 0-based vertex/instance index.
10693 builtin_declaration = true;
Chip Davisc51e5b72019-01-08 16:33:32 -060010694 statement(to_struct_member(type, member_type_id, index, qualifier));
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040010695 builtin_declaration = false;
Bill Hollings103aabf2016-04-06 17:42:27 -040010696}
10697
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020010698void CompilerMSL::emit_struct_padding_target(const SPIRType &type)
10699{
10700 uint32_t struct_size = get_declared_struct_size_msl(type, true, true);
10701 uint32_t target_size = get_extended_decoration(type.self, SPIRVCrossDecorationPaddingTarget);
10702 if (target_size < struct_size)
10703 SPIRV_CROSS_THROW("Cannot pad with negative bytes.");
10704 else if (target_size > struct_size)
10705 statement("char _m0_final_padding[", target_size - struct_size, "];");
10706}
10707
Bill Hollings103aabf2016-04-06 17:42:27 -040010708// Return a MSL qualifier for the specified function attribute member
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010709string CompilerMSL::member_attribute_qualifier(const SPIRType &type, uint32_t index)
10710{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +020010711 auto &execution = get_entry_point();
Bill Hollings103aabf2016-04-06 17:42:27 -040010712
Bill Hollingsd77de7a2017-05-23 13:24:41 -040010713 uint32_t mbr_type_id = type.member_types[index];
10714 auto &mbr_type = get<SPIRType>(mbr_type_id);
10715
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +010010716 BuiltIn builtin = BuiltInMax;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010717 bool is_builtin = is_member_builtin(type, index, &builtin);
Bill Hollings103aabf2016-04-06 17:42:27 -040010718
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020010719 if (has_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary))
Chip Davis2eff4202019-08-04 00:07:20 -050010720 {
10721 string quals = join(
10722 " [[id(", get_extended_member_decoration(type.self, index, SPIRVCrossDecorationResourceIndexPrimary), ")");
10723 if (interlocked_resources.count(
10724 get_extended_member_decoration(type.self, index, SPIRVCrossDecorationInterfaceOrigID)))
10725 quals += ", raster_order_group(0)";
10726 quals += "]]";
10727 return quals;
10728 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010010729
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010730 // Vertex function inputs
10731 if (execution.model == ExecutionModelVertex && type.storage == StorageClassInput)
10732 {
10733 if (is_builtin)
10734 {
10735 switch (builtin)
10736 {
10737 case BuiltInVertexId:
10738 case BuiltInVertexIndex:
Chip Davisfcad0192018-08-28 13:47:29 -050010739 case BuiltInBaseVertex:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010740 case BuiltInInstanceId:
10741 case BuiltInInstanceIndex:
Chip Davisfcad0192018-08-28 13:47:29 -050010742 case BuiltInBaseInstance:
Chip Davis688c5fc2020-02-20 21:38:28 -060010743 if (msl_options.vertex_for_tessellation)
10744 return "";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010745 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -040010746
Chip Davis2ee8ebb2018-08-29 12:05:33 -050010747 case BuiltInDrawIndex:
10748 SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
10749
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010750 default:
10751 return "";
10752 }
10753 }
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010010754
10755 uint32_t locn;
10756 if (is_builtin)
10757 locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
10758 else
10759 locn = get_member_location(type.self, index);
10760
Bill Hollings81757502017-01-29 13:28:20 -050010761 if (locn != k_unknown_location)
10762 return string(" [[attribute(") + convert_to_string(locn) + ")]]";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010763 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010764
Chip Davise75add42019-02-05 18:13:26 -060010765 // Vertex and tessellation evaluation function outputs
Chip Davis688c5fc2020-02-20 21:38:28 -060010766 if (((execution.model == ExecutionModelVertex && !msl_options.vertex_for_tessellation) ||
10767 execution.model == ExecutionModelTessellationEvaluation) &&
Chip Davise75add42019-02-05 18:13:26 -060010768 type.storage == StorageClassOutput)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010769 {
10770 if (is_builtin)
10771 {
10772 switch (builtin)
10773 {
Bill Hollings192bdc92017-05-24 09:31:38 -040010774 case BuiltInPointSize:
10775 // Only mark the PointSize builtin if really rendering points.
10776 // Some shaders may include a PointSize builtin even when used to render
10777 // non-point topologies, and Metal will reject this builtin when compiling
10778 // the shader into a render pipeline that uses a non-point topology.
Hans-Kristian Arntzena803e5a2018-03-09 15:25:25 +010010779 return msl_options.enable_point_size_builtin ? (string(" [[") + builtin_qualifier(builtin) + "]]") : "";
Bill Hollings103aabf2016-04-06 17:42:27 -040010780
Chip Davis0e9ad142018-09-12 18:00:17 -050010781 case BuiltInViewportIndex:
10782 if (!msl_options.supports_msl_version(2, 0))
10783 SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
10784 /* fallthrough */
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010785 case BuiltInPosition:
10786 case BuiltInLayer:
Bill Hollingsd77de7a2017-05-23 13:24:41 -040010787 return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
Bill Hollings103aabf2016-04-06 17:42:27 -040010788
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +010010789 case BuiltInClipDistance:
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +020010790 if (has_member_decoration(type.self, index, DecorationIndex))
10791 return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
10792 else
10793 return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
10794
10795 case BuiltInCullDistance:
10796 if (has_member_decoration(type.self, index, DecorationIndex))
10797 return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +010010798 else
10799 return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
10800
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010801 default:
10802 return "";
10803 }
10804 }
Bill Hollings86dfac12021-09-18 18:55:12 -040010805 string loc_qual = member_location_attribute_qualifier(type, index);
10806 if (!loc_qual.empty())
10807 return join(" [[", loc_qual, "]]");
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010808 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010809
Chip Daviseb89c3a2019-02-03 23:58:46 -060010810 // Tessellation control function inputs
10811 if (execution.model == ExecutionModelTessellationControl && type.storage == StorageClassInput)
10812 {
10813 if (is_builtin)
10814 {
10815 switch (builtin)
10816 {
10817 case BuiltInInvocationId:
10818 case BuiltInPrimitiveId:
Chip Davis688c5fc2020-02-20 21:38:28 -060010819 if (msl_options.multi_patch_workgroup)
10820 return "";
Chip Davis68908352020-11-18 23:16:46 -060010821 return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
Chip Davis9d941572019-05-15 16:03:30 -050010822 case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
10823 case BuiltInSubgroupSize: // FIXME: Should work in any stage
Chip Davis68908352020-11-18 23:16:46 -060010824 if (msl_options.emulate_subgroups)
10825 return "";
Chip Daviseb89c3a2019-02-03 23:58:46 -060010826 return string(" [[") + builtin_qualifier(builtin) + "]]" + (mbr_type.array.empty() ? "" : " ");
10827 case BuiltInPatchVertices:
10828 return "";
10829 // Others come from stage input.
10830 default:
10831 break;
10832 }
10833 }
Chip Davis688c5fc2020-02-20 21:38:28 -060010834 if (msl_options.multi_patch_workgroup)
10835 return "";
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010010836
10837 uint32_t locn;
10838 if (is_builtin)
10839 locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
10840 else
10841 locn = get_member_location(type.self, index);
10842
Chip Daviseb89c3a2019-02-03 23:58:46 -060010843 if (locn != k_unknown_location)
10844 return string(" [[attribute(") + convert_to_string(locn) + ")]]";
10845 }
10846
10847 // Tessellation control function outputs
10848 if (execution.model == ExecutionModelTessellationControl && type.storage == StorageClassOutput)
10849 {
10850 // For this type of shader, we always arrange for it to capture its
10851 // output to a buffer. For this reason, qualifiers are irrelevant here.
10852 return "";
10853 }
10854
Chip Davise75add42019-02-05 18:13:26 -060010855 // Tessellation evaluation function inputs
10856 if (execution.model == ExecutionModelTessellationEvaluation && type.storage == StorageClassInput)
10857 {
10858 if (is_builtin)
10859 {
10860 switch (builtin)
10861 {
10862 case BuiltInPrimitiveId:
10863 case BuiltInTessCoord:
10864 return string(" [[") + builtin_qualifier(builtin) + "]]";
10865 case BuiltInPatchVertices:
10866 return "";
10867 // Others come from stage input.
10868 default:
10869 break;
10870 }
10871 }
10872 // The special control point array must not be marked with an attribute.
10873 if (get_type(type.member_types[index]).basetype == SPIRType::ControlPointArray)
10874 return "";
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010010875
10876 uint32_t locn;
10877 if (is_builtin)
10878 locn = get_or_allocate_builtin_input_member_location(builtin, type.self, index);
10879 else
10880 locn = get_member_location(type.self, index);
10881
Chip Davise75add42019-02-05 18:13:26 -060010882 if (locn != k_unknown_location)
10883 return string(" [[attribute(") + convert_to_string(locn) + ")]]";
10884 }
10885
10886 // Tessellation evaluation function outputs were handled above.
10887
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010888 // Fragment function inputs
10889 if (execution.model == ExecutionModelFragment && type.storage == StorageClassInput)
10890 {
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010891 string quals;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010892 if (is_builtin)
10893 {
10894 switch (builtin)
10895 {
Chip Davis7eecf5a2019-05-31 12:06:20 -050010896 case BuiltInViewIndex:
Chip Daviscab73352020-08-23 16:44:41 -050010897 if (!msl_options.multiview || !msl_options.multiview_layered_rendering)
Chip Davis7eecf5a2019-05-31 12:06:20 -050010898 break;
10899 /* fallthrough */
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010900 case BuiltInFrontFacing:
10901 case BuiltInPointCoord:
Bill Hollings8f2dec32016-07-04 11:49:46 -040010902 case BuiltInFragCoord:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010903 case BuiltInSampleId:
10904 case BuiltInSampleMask:
10905 case BuiltInLayer:
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010906 case BuiltInBaryCoordNV:
10907 case BuiltInBaryCoordNoPerspNV:
Chip Davis9e6469b2018-09-04 16:08:22 -050010908 quals = builtin_qualifier(builtin);
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010909 break;
Bill Hollings103aabf2016-04-06 17:42:27 -040010910
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +010010911 case BuiltInClipDistance:
Hans-Kristian Arntzen58262982021-04-14 13:51:55 +020010912 return join(" [[user(clip", get_member_decoration(type.self, index, DecorationIndex), ")]]");
10913 case BuiltInCullDistance:
10914 return join(" [[user(cull", get_member_decoration(type.self, index, DecorationIndex), ")]]");
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +010010915
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010916 default:
Chip Davis9e6469b2018-09-04 16:08:22 -050010917 break;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010918 }
10919 }
Chip Davis9e6469b2018-09-04 16:08:22 -050010920 else
Bill Hollings86dfac12021-09-18 18:55:12 -040010921 quals = member_location_attribute_qualifier(type, index);
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010922
10923 if (builtin == BuiltInBaryCoordNV || builtin == BuiltInBaryCoordNoPerspNV)
10924 {
10925 if (has_member_decoration(type.self, index, DecorationFlat) ||
10926 has_member_decoration(type.self, index, DecorationCentroid) ||
10927 has_member_decoration(type.self, index, DecorationSample) ||
10928 has_member_decoration(type.self, index, DecorationNoPerspective))
10929 {
10930 // NoPerspective is baked into the builtin type.
Hans-Kristian Arntzenb4e01632019-06-21 16:02:22 +020010931 SPIRV_CROSS_THROW(
10932 "Flat, Centroid, Sample, NoPerspective decorations are not supported for BaryCoord inputs.");
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010933 }
10934 }
10935
Chip Davis9e6469b2018-09-04 16:08:22 -050010936 // Don't bother decorating integers with the 'flat' attribute; it's
10937 // the default (in fact, the only option). Also don't bother with the
10938 // FragCoord builtin; it's always noperspective on Metal.
10939 if (!type_is_integral(mbr_type) && (!is_builtin || builtin != BuiltInFragCoord))
10940 {
10941 if (has_member_decoration(type.self, index, DecorationFlat))
10942 {
10943 if (!quals.empty())
10944 quals += ", ";
10945 quals += "flat";
10946 }
10947 else if (has_member_decoration(type.self, index, DecorationCentroid))
10948 {
10949 if (!quals.empty())
10950 quals += ", ";
10951 if (has_member_decoration(type.self, index, DecorationNoPerspective))
10952 quals += "centroid_no_perspective";
10953 else
10954 quals += "centroid_perspective";
10955 }
10956 else if (has_member_decoration(type.self, index, DecorationSample))
10957 {
10958 if (!quals.empty())
10959 quals += ", ";
10960 if (has_member_decoration(type.self, index, DecorationNoPerspective))
10961 quals += "sample_no_perspective";
10962 else
10963 quals += "sample_perspective";
10964 }
10965 else if (has_member_decoration(type.self, index, DecorationNoPerspective))
10966 {
10967 if (!quals.empty())
10968 quals += ", ";
10969 quals += "center_no_perspective";
10970 }
10971 }
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020010972
Chip Davis9e6469b2018-09-04 16:08:22 -050010973 if (!quals.empty())
10974 return " [[" + quals + "]]";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010975 }
Bill Hollings103aabf2016-04-06 17:42:27 -040010976
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010977 // Fragment function outputs
10978 if (execution.model == ExecutionModelFragment && type.storage == StorageClassOutput)
10979 {
10980 if (is_builtin)
10981 {
10982 switch (builtin)
10983 {
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020010984 case BuiltInFragStencilRefEXT:
Chip Davisb29f83c2020-04-10 01:13:33 -050010985 // Similar to PointSize, only mark FragStencilRef if there's a stencil buffer.
10986 // Some shaders may include a FragStencilRef builtin even when used to render
10987 // without a stencil attachment, and Metal will reject this builtin
10988 // when compiling the shader into a render pipeline that does not set
10989 // stencilAttachmentPixelFormat.
10990 if (!msl_options.enable_frag_stencil_ref_builtin)
10991 return "";
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020010992 if (!msl_options.supports_msl_version(2, 1))
10993 SPIRV_CROSS_THROW("Stencil export only supported in MSL 2.1 and up.");
10994 return string(" [[") + builtin_qualifier(builtin) + "]]";
10995
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020010996 case BuiltInFragDepth:
Chip Davisb29f83c2020-04-10 01:13:33 -050010997 // Ditto FragDepth.
10998 if (!msl_options.enable_frag_depth_builtin)
10999 return "";
11000 /* fallthrough */
11001 case BuiltInSampleMask:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011002 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -040011003
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011004 default:
11005 return "";
11006 }
11007 }
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011008 uint32_t locn = get_member_location(type.self, index);
Chip Davisb29f83c2020-04-10 01:13:33 -050011009 // Metal will likely complain about missing color attachments, too.
11010 if (locn != k_unknown_location && !(msl_options.enable_frag_output_mask & (1 << locn)))
11011 return "";
Hans-Kristian Arntzena6e211e2018-04-03 15:56:22 +020011012 if (locn != k_unknown_location && has_member_decoration(type.self, index, DecorationIndex))
Hans-Kristian Arntzen9c2761f2018-04-10 12:32:14 +020011013 return join(" [[color(", locn, "), index(", get_member_decoration(type.self, index, DecorationIndex),
11014 ")]]");
Hans-Kristian Arntzena6e211e2018-04-03 15:56:22 +020011015 else if (locn != k_unknown_location)
11016 return join(" [[color(", locn, ")]]");
11017 else if (has_member_decoration(type.self, index, DecorationIndex))
11018 return join(" [[index(", get_member_decoration(type.self, index, DecorationIndex), ")]]");
11019 else
11020 return "";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011021 }
11022
Corentin Wallez6d653aa2017-01-22 13:09:04 -050011023 // Compute function inputs
11024 if (execution.model == ExecutionModelGLCompute && type.storage == StorageClassInput)
11025 {
11026 if (is_builtin)
11027 {
11028 switch (builtin)
11029 {
Chip Davis68908352020-11-18 23:16:46 -060011030 case BuiltInNumSubgroups:
11031 case BuiltInSubgroupId:
11032 case BuiltInSubgroupLocalInvocationId: // FIXME: Should work in any stage
11033 case BuiltInSubgroupSize: // FIXME: Should work in any stage
11034 if (msl_options.emulate_subgroups)
11035 break;
11036 /* fallthrough */
Corentin Wallez6d653aa2017-01-22 13:09:04 -050011037 case BuiltInGlobalInvocationId:
Hans-Kristian Arntzenaab31072017-09-29 12:16:53 +020011038 case BuiltInWorkgroupId:
11039 case BuiltInNumWorkgroups:
Corentin Wallezd8278a82017-01-26 20:22:31 -050011040 case BuiltInLocalInvocationId:
11041 case BuiltInLocalInvocationIndex:
Corentin Wallez6d653aa2017-01-22 13:09:04 -050011042 return string(" [[") + builtin_qualifier(builtin) + "]]";
11043
11044 default:
11045 return "";
11046 }
11047 }
11048 }
11049
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011050 return "";
Bill Hollings103aabf2016-04-06 17:42:27 -040011051}
11052
Bill Hollings86dfac12021-09-18 18:55:12 -040011053// A user-defined output variable is considered to match an input variable in the subsequent
11054// stage if the two variables are declared with the same Location and Component decoration and
11055// match in type and decoration, except that interpolation decorations are not required to match.
11056// For the purposes of interface matching, variables declared without a Component decoration are
11057// considered to have a Component decoration of zero.
11058string CompilerMSL::member_location_attribute_qualifier(const SPIRType &type, uint32_t index)
11059{
11060 string quals;
11061 uint32_t comp;
11062 uint32_t locn = get_member_location(type.self, index, &comp);
11063 if (locn != k_unknown_location)
11064 {
11065 quals += "user(locn";
11066 quals += convert_to_string(locn);
11067 if (comp != k_unknown_component && comp != 0)
11068 {
11069 quals += "_";
11070 quals += convert_to_string(comp);
11071 }
11072 quals += ")";
11073 }
11074 return quals;
11075}
11076
Bill Hollingsaca1b552016-12-04 12:32:58 -050011077// Returns the location decoration of the member with the specified index in the specified type.
11078// If the location of the member has been explicitly set, that location is used. If not, this
11079// function assumes the members are ordered in their location order, and simply returns the
11080// index as the location.
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011081uint32_t CompilerMSL::get_member_location(uint32_t type_id, uint32_t index, uint32_t *comp) const
Bill Hollings103aabf2016-04-06 17:42:27 -040011082{
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011083 if (comp)
Bill Hollingsaca1b552016-12-04 12:32:58 -050011084 {
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011085 if (has_member_decoration(type_id, index, DecorationComponent))
11086 *comp = get_member_decoration(type_id, index, DecorationComponent);
11087 else
11088 *comp = k_unknown_component;
Bill Hollingsaca1b552016-12-04 12:32:58 -050011089 }
11090
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011091 if (has_member_decoration(type_id, index, DecorationLocation))
11092 return get_member_decoration(type_id, index, DecorationLocation);
11093 else
11094 return k_unknown_location;
11095}
11096
11097uint32_t CompilerMSL::get_or_allocate_builtin_input_member_location(spv::BuiltIn builtin,
11098 uint32_t type_id, uint32_t index,
11099 uint32_t *comp)
11100{
11101 uint32_t loc = get_member_location(type_id, index, comp);
11102 if (loc != k_unknown_location)
11103 return loc;
11104
11105 if (comp)
11106 *comp = k_unknown_component;
11107
11108 // Late allocation. Find a location which is unused by the application.
11109 // This can happen for built-in inputs in tessellation which are mixed and matched with user inputs.
11110 auto &mbr_type = get<SPIRType>(get<SPIRType>(type_id).member_types[index]);
11111 uint32_t count = type_to_location_count(mbr_type);
11112
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011113 loc = 0;
Hans-Kristian Arntzen46c48ee2021-04-08 11:47:35 +020011114
11115 const auto location_range_in_use = [this](uint32_t location, uint32_t location_count) -> bool {
11116 for (uint32_t i = 0; i < location_count; i++)
11117 if (location_inputs_in_use.count(location + i) != 0)
11118 return true;
11119 return false;
11120 };
11121
11122 while (location_range_in_use(loc, count))
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011123 loc++;
11124
11125 set_member_decoration(type_id, index, DecorationLocation, loc);
11126
11127 // Triangle tess level inputs are shared in one packed float4,
11128 // mark both builtins as sharing one location.
11129 if (get_execution_mode_bitset().get(ExecutionModeTriangles) &&
11130 (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
11131 {
11132 builtin_to_automatic_input_location[BuiltInTessLevelInner] = loc;
11133 builtin_to_automatic_input_location[BuiltInTessLevelOuter] = loc;
11134 }
11135 else
11136 builtin_to_automatic_input_location[builtin] = loc;
11137
Hans-Kristian Arntzenfaf80b02021-04-09 18:55:10 +020011138 mark_location_as_used_by_shader(loc, mbr_type, StorageClassInput, true);
Hans-Kristian Arntzence552f42021-02-17 12:21:21 +010011139 return loc;
Bill Hollings103aabf2016-04-06 17:42:27 -040011140}
11141
Bill Hollings103aabf2016-04-06 17:42:27 -040011142// Returns the type declaration for a function, including the
11143// entry type if the current function is the entry point function
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011144string CompilerMSL::func_type_decl(SPIRType &type)
Bill Hollings103aabf2016-04-06 17:42:27 -040011145{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011146 // The regular function return type. If not processing the entry point function, that's all we need
Hans-Kristian Arntzen9fa91f72018-02-05 09:34:54 +010011147 string return_type = type_to_glsl(type) + type_to_array_glsl(type);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011148 if (!processing_entry_point)
11149 return return_type;
Bill Hollings103aabf2016-04-06 17:42:27 -040011150
Bill Hollingsac238b82018-07-26 00:50:33 -040011151 // If an outgoing interface block has been defined, and it should be returned, override the entry point return type
Bill Hollings0d6202e2018-07-26 16:40:32 -040011152 bool ep_should_return_output = !get_is_rasterization_disabled();
Bill Hollingsac238b82018-07-26 00:50:33 -040011153 if (stage_out_var_id && ep_should_return_output)
Chip Davisc51e5b72019-01-08 16:33:32 -060011154 return_type = type_to_glsl(get_stage_out_struct_type()) + type_to_array_glsl(type);
Bill Hollings103aabf2016-04-06 17:42:27 -040011155
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011156 // Prepend a entry type, based on the execution model
11157 string entry_type;
Bill Hollingsac238b82018-07-26 00:50:33 -040011158 auto &execution = get_entry_point();
Bill Hollingsac00c602016-10-24 09:24:24 -040011159 switch (execution.model)
11160 {
11161 case ExecutionModelVertex:
Chip Davis688c5fc2020-02-20 21:38:28 -060011162 if (msl_options.vertex_for_tessellation && !msl_options.supports_msl_version(1, 2))
11163 SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
11164 entry_type = msl_options.vertex_for_tessellation ? "kernel" : "vertex";
Bill Hollingsac00c602016-10-24 09:24:24 -040011165 break;
Chip Davise75add42019-02-05 18:13:26 -060011166 case ExecutionModelTessellationEvaluation:
11167 if (!msl_options.supports_msl_version(1, 2))
11168 SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
11169 if (execution.flags.get(ExecutionModeIsolines))
11170 SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
11171 if (msl_options.is_ios())
11172 entry_type =
11173 join("[[ patch(", execution.flags.get(ExecutionModeTriangles) ? "triangle" : "quad", ") ]] vertex");
11174 else
11175 entry_type = join("[[ patch(", execution.flags.get(ExecutionModeTriangles) ? "triangle" : "quad", ", ",
11176 execution.output_vertices, ") ]] vertex");
11177 break;
Bill Hollingsac00c602016-10-24 09:24:24 -040011178 case ExecutionModelFragment:
Bill Hollings248e9ae2021-11-12 14:17:00 -050011179 entry_type = uses_explicit_early_fragment_test() ? "[[ early_fragment_tests ]] fragment" : "fragment";
Bill Hollingsac00c602016-10-24 09:24:24 -040011180 break;
Chip Daviseb89c3a2019-02-03 23:58:46 -060011181 case ExecutionModelTessellationControl:
11182 if (!msl_options.supports_msl_version(1, 2))
11183 SPIRV_CROSS_THROW("Tessellation requires Metal 1.2.");
Chip Davis83b7e662019-02-11 17:21:36 -060011184 if (execution.flags.get(ExecutionModeIsolines))
11185 SPIRV_CROSS_THROW("Metal does not support isoline tessellation.");
Chip Daviseb89c3a2019-02-03 23:58:46 -060011186 /* fallthrough */
Bill Hollingsac00c602016-10-24 09:24:24 -040011187 case ExecutionModelGLCompute:
11188 case ExecutionModelKernel:
11189 entry_type = "kernel";
11190 break;
11191 default:
11192 entry_type = "unknown";
11193 break;
11194 }
Bill Hollings103aabf2016-04-06 17:42:27 -040011195
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011196 return entry_type + " " + return_type;
Bill Hollings103aabf2016-04-06 17:42:27 -040011197}
11198
Bill Hollings248e9ae2021-11-12 14:17:00 -050011199bool CompilerMSL::uses_explicit_early_fragment_test()
11200{
11201 auto &ep_flags = get_entry_point().flags;
11202 return ep_flags.get(ExecutionModeEarlyFragmentTests) || ep_flags.get(ExecutionModePostDepthCoverage);
11203}
11204
Chip Davis3bfb2f92018-12-03 02:06:33 -060011205// In MSL, address space qualifiers are required for all pointer or reference variables
Corentin Wallez789eb432017-01-26 19:40:56 -050011206string CompilerMSL::get_argument_address_space(const SPIRVariable &argument)
11207{
11208 const auto &type = get<SPIRType>(argument.basetype);
Chip Davisdf18d982019-07-26 01:06:35 -050011209 return get_type_address_space(type, argument.self, true);
Corentin Wallez789eb432017-01-26 19:40:56 -050011210}
11211
Chip Davisdf18d982019-07-26 01:06:35 -050011212string CompilerMSL::get_type_address_space(const SPIRType &type, uint32_t id, bool argument)
Chip Davis3bfb2f92018-12-03 02:06:33 -060011213{
Chip Davis058f1a02019-07-10 11:17:40 -050011214 // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
11215 Bitset flags;
Chip Davisdf18d982019-07-26 01:06:35 -050011216 auto *var = maybe_get<SPIRVariable>(id);
11217 if (var && type.basetype == SPIRType::Struct &&
Chip Davis058f1a02019-07-10 11:17:40 -050011218 (has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock)))
11219 flags = get_buffer_block_flags(id);
11220 else
11221 flags = get_decoration_bitset(id);
11222
11223 const char *addr_space = nullptr;
Chip Davis3bfb2f92018-12-03 02:06:33 -060011224 switch (type.storage)
11225 {
11226 case StorageClassWorkgroup:
Chip Davis058f1a02019-07-10 11:17:40 -050011227 addr_space = "threadgroup";
11228 break;
Chip Davis3bfb2f92018-12-03 02:06:33 -060011229
11230 case StorageClassStorageBuffer:
Chip Davisdf18d982019-07-26 01:06:35 -050011231 {
11232 // For arguments from variable pointers, we use the write count deduction, so
11233 // we should not assume any constness here. Only for global SSBOs.
11234 bool readonly = false;
11235 if (!var || has_decoration(type.self, DecorationBlock))
11236 readonly = flags.get(DecorationNonWritable);
11237
11238 addr_space = readonly ? "const device" : "device";
Chip Davis058f1a02019-07-10 11:17:40 -050011239 break;
Chip Davisdf18d982019-07-26 01:06:35 -050011240 }
Chip Davis3bfb2f92018-12-03 02:06:33 -060011241
11242 case StorageClassUniform:
11243 case StorageClassUniformConstant:
11244 case StorageClassPushConstant:
11245 if (type.basetype == SPIRType::Struct)
11246 {
11247 bool ssbo = has_decoration(type.self, DecorationBufferBlock);
Chip Davis3bfb2f92018-12-03 02:06:33 -060011248 if (ssbo)
Chip Davis058f1a02019-07-10 11:17:40 -050011249 addr_space = flags.get(DecorationNonWritable) ? "const device" : "device";
Chip Davis3bfb2f92018-12-03 02:06:33 -060011250 else
Chip Davis058f1a02019-07-10 11:17:40 -050011251 addr_space = "constant";
Chip Davis3bfb2f92018-12-03 02:06:33 -060011252 }
Chip Davisdf18d982019-07-26 01:06:35 -050011253 else if (!argument)
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020011254 {
Chip Davis058f1a02019-07-10 11:17:40 -050011255 addr_space = "constant";
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020011256 }
11257 else if (type_is_msl_framebuffer_fetch(type))
11258 {
11259 // Subpass inputs are passed around by value.
11260 addr_space = "";
11261 }
Chip Davis058f1a02019-07-10 11:17:40 -050011262 break;
Chip Davis3bfb2f92018-12-03 02:06:33 -060011263
11264 case StorageClassFunction:
11265 case StorageClassGeneric:
Chip Davisdf18d982019-07-26 01:06:35 -050011266 break;
11267
11268 case StorageClassInput:
11269 if (get_execution_model() == ExecutionModelTessellationControl && var &&
11270 var->basevariable == stage_in_ptr_var_id)
Chip Davis688c5fc2020-02-20 21:38:28 -060011271 addr_space = msl_options.multi_patch_workgroup ? "constant" : "threadgroup";
Chip Davisaca9b682020-11-02 20:56:46 -060011272 if (get_execution_model() == ExecutionModelFragment && var && var->basevariable == stage_in_var_id)
11273 addr_space = "thread";
Chip Davis058f1a02019-07-10 11:17:40 -050011274 break;
Chip Davis3bfb2f92018-12-03 02:06:33 -060011275
Chip Davisc51e5b72019-01-08 16:33:32 -060011276 case StorageClassOutput:
11277 if (capture_output_to_buffer)
Hans-Kristian Arntzene7b37392021-04-06 13:28:45 +020011278 {
11279 if (var && type.storage == StorageClassOutput)
11280 {
Hans-Kristian Arntzena393de32021-04-06 14:12:24 +020011281 bool is_masked = is_stage_output_variable_masked(*var);
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +020011282
Hans-Kristian Arntzene7b37392021-04-06 13:28:45 +020011283 if (is_masked)
11284 {
11285 if (is_tessellation_shader())
11286 addr_space = "threadgroup";
11287 else
11288 addr_space = "thread";
11289 }
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +020011290 else if (variable_decl_is_remapped_storage(*var, StorageClassWorkgroup))
11291 addr_space = "threadgroup";
Hans-Kristian Arntzene7b37392021-04-06 13:28:45 +020011292 }
11293
11294 if (!addr_space)
11295 addr_space = "device";
11296 }
Chip Davisc51e5b72019-01-08 16:33:32 -060011297 break;
11298
Chip Davis3bfb2f92018-12-03 02:06:33 -060011299 default:
11300 break;
11301 }
11302
Chip Davis058f1a02019-07-10 11:17:40 -050011303 if (!addr_space)
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010011304 {
Chip Davisdf18d982019-07-26 01:06:35 -050011305 // No address space for plain values.
11306 addr_space = type.pointer || (argument && type.basetype == SPIRType::ControlPointArray) ? "thread" : "";
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010011307 }
Chip Davis058f1a02019-07-10 11:17:40 -050011308
11309 return join(flags.get(DecorationVolatile) || flags.get(DecorationCoherent) ? "volatile " : "", addr_space);
11310}
11311
11312const char *CompilerMSL::to_restrict(uint32_t id, bool space)
11313{
11314 // This can be called for variable pointer contexts as well, so be very careful about which method we choose.
11315 Bitset flags;
11316 if (ir.ids[id].get_type() == TypeVariable)
11317 {
11318 uint32_t type_id = expression_type_id(id);
11319 auto &type = expression_type(id);
11320 if (type.basetype == SPIRType::Struct &&
11321 (has_decoration(type_id, DecorationBlock) || has_decoration(type_id, DecorationBufferBlock)))
11322 flags = get_buffer_block_flags(id);
11323 else
11324 flags = get_decoration_bitset(id);
11325 }
11326 else
11327 flags = get_decoration_bitset(id);
11328
11329 return flags.get(DecorationRestrict) ? (space ? "restrict " : "restrict") : "";
Chip Davis3bfb2f92018-12-03 02:06:33 -060011330}
11331
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011332string CompilerMSL::entry_point_arg_stage_in()
Bill Hollings103aabf2016-04-06 17:42:27 -040011333{
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011334 string decl;
Bill Hollings103aabf2016-04-06 17:42:27 -040011335
Chip Davis688c5fc2020-02-20 21:38:28 -060011336 if (get_execution_model() == ExecutionModelTessellationControl && msl_options.multi_patch_workgroup)
11337 return decl;
11338
Bill Hollingse27a5f72017-01-01 14:43:20 -050011339 // Stage-in structure
Chip Davise75add42019-02-05 18:13:26 -060011340 uint32_t stage_in_id;
11341 if (get_execution_model() == ExecutionModelTessellationEvaluation)
11342 stage_in_id = patch_stage_in_var_id;
11343 else
11344 stage_in_id = stage_in_var_id;
11345
11346 if (stage_in_id)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011347 {
Chip Davise75add42019-02-05 18:13:26 -060011348 auto &var = get<SPIRVariable>(stage_in_id);
Chip Davis3bfb2f92018-12-03 02:06:33 -060011349 auto &type = get_variable_data_type(var);
Bill Hollings103aabf2016-04-06 17:42:27 -040011350
Hans-Kristian Arntzen437fc872019-01-18 16:27:57 +010011351 add_resource_name(var.self);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011352 decl = join(type_to_glsl(type), " ", to_name(var.self), " [[stage_in]]");
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011353 }
Bill Hollings103aabf2016-04-06 17:42:27 -040011354
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011355 return decl;
11356}
Arseny Kapoulkine05036142018-01-25 18:19:38 -080011357
Chip Davis5e13f7f2020-07-22 15:25:10 -060011358// Returns true if this input builtin should be a direct parameter on a shader function parameter list,
11359// and false for builtins that should be passed or calculated some other way.
11360bool CompilerMSL::is_direct_input_builtin(BuiltIn bi_type)
11361{
11362 switch (bi_type)
11363 {
Chip Davis688c5fc2020-02-20 21:38:28 -060011364 // Vertex function in
11365 case BuiltInVertexId:
11366 case BuiltInVertexIndex:
11367 case BuiltInBaseVertex:
11368 case BuiltInInstanceId:
11369 case BuiltInInstanceIndex:
11370 case BuiltInBaseInstance:
11371 return get_execution_model() != ExecutionModelVertex || !msl_options.vertex_for_tessellation;
Chip Davis5e13f7f2020-07-22 15:25:10 -060011372 // Tess. control function in
11373 case BuiltInPosition:
11374 case BuiltInPointSize:
11375 case BuiltInClipDistance:
11376 case BuiltInCullDistance:
11377 case BuiltInPatchVertices:
11378 return false;
Chip Davis688c5fc2020-02-20 21:38:28 -060011379 case BuiltInInvocationId:
11380 case BuiltInPrimitiveId:
11381 return get_execution_model() != ExecutionModelTessellationControl || !msl_options.multi_patch_workgroup;
Chip Davis5e13f7f2020-07-22 15:25:10 -060011382 // Tess. evaluation function in
11383 case BuiltInTessLevelInner:
11384 case BuiltInTessLevelOuter:
11385 return false;
11386 // Fragment function in
11387 case BuiltInSamplePosition:
11388 case BuiltInHelperInvocation:
11389 case BuiltInBaryCoordNV:
11390 case BuiltInBaryCoordNoPerspNV:
11391 return false;
11392 case BuiltInViewIndex:
Chip Daviscab73352020-08-23 16:44:41 -050011393 return get_execution_model() == ExecutionModelFragment && msl_options.multiview &&
11394 msl_options.multiview_layered_rendering;
Chip Davis68908352020-11-18 23:16:46 -060011395 // Compute function in
11396 case BuiltInSubgroupId:
11397 case BuiltInNumSubgroups:
11398 return !msl_options.emulate_subgroups;
Chip Davis5e13f7f2020-07-22 15:25:10 -060011399 // Any stage function in
11400 case BuiltInDeviceIndex:
11401 case BuiltInSubgroupEqMask:
11402 case BuiltInSubgroupGeMask:
11403 case BuiltInSubgroupGtMask:
11404 case BuiltInSubgroupLeMask:
11405 case BuiltInSubgroupLtMask:
11406 return false;
Chip Davis5e13f7f2020-07-22 15:25:10 -060011407 case BuiltInSubgroupSize:
Chip Davis68908352020-11-18 23:16:46 -060011408 if (msl_options.fixed_subgroup_size != 0)
11409 return false;
11410 /* fallthrough */
11411 case BuiltInSubgroupLocalInvocationId:
11412 return !msl_options.emulate_subgroups;
Chip Davis5e13f7f2020-07-22 15:25:10 -060011413 default:
11414 return true;
11415 }
11416}
11417
Chip Davisfd738e32020-11-20 15:41:46 -060011418// Returns true if this is a fragment shader that runs per sample, and false otherwise.
11419bool CompilerMSL::is_sample_rate() const
11420{
11421 auto &caps = get_declared_capabilities();
11422 return get_execution_model() == ExecutionModelFragment &&
11423 (msl_options.force_sample_rate_shading ||
11424 std::find(caps.begin(), caps.end(), CapabilitySampleRateShading) != caps.end() ||
11425 (msl_options.use_framebuffer_fetch_subpasses && need_subpass_input));
11426}
11427
丛越d52ec1e2021-10-21 17:46:45 +080011428bool CompilerMSL::is_intersection_query() const
11429{
11430 auto &caps = get_declared_capabilities();
11431 return std::find(caps.begin(), caps.end(), CapabilityRayQueryKHR) != caps.end();
11432}
11433
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011434void CompilerMSL::entry_point_args_builtin(string &ep_args)
11435{
Arseny Kapoulkine05036142018-01-25 18:19:38 -080011436 // Builtin variables
Chip Davis1df47db2019-07-10 22:42:39 -050011437 SmallVector<pair<SPIRVariable *, BuiltIn>, 8> active_builtins;
Chip Daviseb89c3a2019-02-03 23:58:46 -060011438 ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
Hans-Kristian Arntzenc8837d72021-01-07 10:27:14 +010011439 if (var.storage != StorageClassInput)
11440 return;
11441
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +020011442 auto bi_type = BuiltIn(get_decoration(var_id, DecorationBuiltIn));
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010011443
11444 // Don't emit SamplePosition as a separate parameter. In the entry
11445 // point, we get that by calling get_sample_position() on the sample ID.
Hans-Kristian Arntzenc8837d72021-01-07 10:27:14 +010011446 if (is_builtin_variable(var) &&
Chip Davise75add42019-02-05 18:13:26 -060011447 get_variable_data_type(var).basetype != SPIRType::Struct &&
11448 get_variable_data_type(var).basetype != SPIRType::ControlPointArray)
Arseny Kapoulkine05036142018-01-25 18:19:38 -080011449 {
Hans-Kristian Arntzen314efdc2019-05-31 13:19:33 +020011450 // If the builtin is not part of the active input builtin set, don't emit it.
11451 // Relevant for multiple entry-point modules which might declare unused builtins.
11452 if (!active_input_builtins.get(bi_type) || !interface_variable_exists_in_entry_point(var_id))
11453 return;
11454
Chip Davis1df47db2019-07-10 22:42:39 -050011455 // Remember this variable. We may need to correct its type.
11456 active_builtins.push_back(make_pair(&var, bi_type));
11457
Chip Davis5e13f7f2020-07-22 15:25:10 -060011458 if (is_direct_input_builtin(bi_type))
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010011459 {
11460 if (!ep_args.empty())
11461 ep_args += ", ";
Hans-Kristian Arntzen61f1d8b2018-11-28 15:18:43 +010011462
Lukas Hermanns50ac6862019-09-18 14:03:54 -040011463 // Handle HLSL-style 0-based vertex/instance index.
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040011464 builtin_declaration = true;
Nikita Fediuchina6698402021-12-17 22:51:18 +020011465
11466 // Handle different MSL gl_TessCoord types. (float2, float3)
11467 if (bi_type == BuiltInTessCoord && get_entry_point().flags.get(ExecutionModeQuads))
Nikita Fediuchin2acf0e72021-12-20 22:58:21 +020011468 ep_args += "float2 " + to_expression(var_id) + "In";
11469 else
11470 ep_args += builtin_type_decl(bi_type, var_id) + " " + to_expression(var_id);
Nikita Fediuchina6698402021-12-17 22:51:18 +020011471
Chip Davis1df47db2019-07-10 22:42:39 -050011472 ep_args += " [[" + builtin_qualifier(bi_type);
11473 if (bi_type == BuiltInSampleMask && get_entry_point().flags.get(ExecutionModePostDepthCoverage))
11474 {
11475 if (!msl_options.supports_msl_version(2))
Chip Davisd48d2a92020-10-27 21:25:43 -050011476 SPIRV_CROSS_THROW("Post-depth coverage requires MSL 2.0.");
11477 if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
11478 SPIRV_CROSS_THROW("Post-depth coverage on Mac requires MSL 2.3.");
Chip Davis1df47db2019-07-10 22:42:39 -050011479 ep_args += ", post_depth_coverage";
11480 }
11481 ep_args += "]]";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011482 builtin_declaration = false;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011483 }
11484 }
Chip Davisfb5ee4c2019-07-22 13:08:04 -050011485
Hans-Kristian Arntzenc8837d72021-01-07 10:27:14 +010011486 if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInDispatchBase))
Chip Davisfb5ee4c2019-07-22 13:08:04 -050011487 {
11488 // This is a special implicit builtin, not corresponding to any SPIR-V builtin,
Chip Davis688c5fc2020-02-20 21:38:28 -060011489 // which holds the base that was passed to vkCmdDispatchBase() or vkCmdDrawIndexed(). If it's present,
Chip Davisfb5ee4c2019-07-22 13:08:04 -050011490 // assume we emitted it for a good reason.
11491 assert(msl_options.supports_msl_version(1, 2));
11492 if (!ep_args.empty())
11493 ep_args += ", ";
11494
11495 ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_origin]]";
11496 }
Chip Davis688c5fc2020-02-20 21:38:28 -060011497
Hans-Kristian Arntzenc8837d72021-01-07 10:27:14 +010011498 if (has_extended_decoration(var_id, SPIRVCrossDecorationBuiltInStageInputSize))
Chip Davis688c5fc2020-02-20 21:38:28 -060011499 {
11500 // This is another special implicit builtin, not corresponding to any SPIR-V builtin,
11501 // which holds the number of vertices and instances to draw. If it's present,
11502 // assume we emitted it for a good reason.
11503 assert(msl_options.supports_msl_version(1, 2));
11504 if (!ep_args.empty())
11505 ep_args += ", ";
11506
11507 ep_args += type_to_glsl(get_variable_data_type(var)) + " " + to_expression(var_id) + " [[grid_size]]";
11508 }
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010011509 });
Bill Hollings103aabf2016-04-06 17:42:27 -040011510
Chip Davis1df47db2019-07-10 22:42:39 -050011511 // Correct the types of all encountered active builtins. We couldn't do this before
11512 // because ensure_correct_builtin_type() may increase the bound, which isn't allowed
11513 // while iterating over IDs.
11514 for (auto &var : active_builtins)
11515 var.first->basetype = ensure_correct_builtin_type(var.first->basetype, var.second);
11516
Lukas Hermanns50ac6862019-09-18 14:03:54 -040011517 // Handle HLSL-style 0-based vertex/instance index.
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020011518 if (needs_base_vertex_arg == TriState::Yes)
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040011519 ep_args += built_in_func_arg(BuiltInBaseVertex, !ep_args.empty());
Bill Hollings81757502017-01-29 13:28:20 -050011520
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020011521 if (needs_base_instance_arg == TriState::Yes)
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040011522 ep_args += built_in_func_arg(BuiltInBaseInstance, !ep_args.empty());
Bill Hollings81757502017-01-29 13:28:20 -050011523
Chip Davisc51e5b72019-01-08 16:33:32 -060011524 if (capture_output_to_buffer)
11525 {
Chip Davis056c0e22019-02-06 15:17:14 -060011526 // Add parameters to hold the indirect draw parameters and the shader output. This has to be handled
Chip Davisc51e5b72019-01-08 16:33:32 -060011527 // specially because it needs to be a pointer, not a reference.
11528 if (stage_out_var_id)
11529 {
11530 if (!ep_args.empty())
11531 ep_args += ", ";
Chip Davis056c0e22019-02-06 15:17:14 -060011532 ep_args += join("device ", type_to_glsl(get_stage_out_struct_type()), "* ", output_buffer_var_name,
Chip Daviseb89c3a2019-02-03 23:58:46 -060011533 " [[buffer(", msl_options.shader_output_buffer_index, ")]]");
11534 }
11535
Michael Barriault105bfd32019-04-16 17:56:02 +010011536 if (get_execution_model() == ExecutionModelTessellationControl)
Chip Daviseb89c3a2019-02-03 23:58:46 -060011537 {
11538 if (!ep_args.empty())
11539 ep_args += ", ";
Chip Davis056c0e22019-02-06 15:17:14 -060011540 ep_args +=
Hans-Kristian Arntzende1148b2019-04-23 12:21:53 +020011541 join("constant uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
Chip Davisc51e5b72019-01-08 16:33:32 -060011542 }
Chip Davis688c5fc2020-02-20 21:38:28 -060011543 else if (stage_out_var_id &&
11544 !(get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation))
Michael Barriault82b4ad82019-04-16 19:13:57 +010011545 {
11546 if (!ep_args.empty())
11547 ep_args += ", ";
11548 ep_args +=
Hans-Kristian Arntzende1148b2019-04-23 12:21:53 +020011549 join("device uint* spvIndirectParams [[buffer(", msl_options.indirect_params_buffer_index, ")]]");
Michael Barriault82b4ad82019-04-16 19:13:57 +010011550 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060011551
Chip Davis688c5fc2020-02-20 21:38:28 -060011552 if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation &&
11553 (active_input_builtins.get(BuiltInVertexIndex) || active_input_builtins.get(BuiltInVertexId)) &&
11554 msl_options.vertex_index_type != Options::IndexType::None)
11555 {
11556 // Add the index buffer so we can set gl_VertexIndex correctly.
11557 if (!ep_args.empty())
11558 ep_args += ", ";
11559 switch (msl_options.vertex_index_type)
11560 {
11561 case Options::IndexType::None:
11562 break;
11563 case Options::IndexType::UInt16:
11564 ep_args += join("const device ushort* ", index_buffer_var_name, " [[buffer(",
11565 msl_options.shader_index_buffer_index, ")]]");
11566 break;
11567 case Options::IndexType::UInt32:
11568 ep_args += join("const device uint* ", index_buffer_var_name, " [[buffer(",
11569 msl_options.shader_index_buffer_index, ")]]");
11570 break;
11571 }
11572 }
11573
Chip Daviseb89c3a2019-02-03 23:58:46 -060011574 // Tessellation control shaders get three additional parameters:
11575 // a buffer to hold the per-patch data, a buffer to hold the per-patch
11576 // tessellation levels, and a block of workgroup memory to hold the
11577 // input control point data.
11578 if (get_execution_model() == ExecutionModelTessellationControl)
11579 {
11580 if (patch_stage_out_var_id)
11581 {
11582 if (!ep_args.empty())
11583 ep_args += ", ";
Chip Davis0bb6bbd2019-02-11 17:18:54 -060011584 ep_args +=
11585 join("device ", type_to_glsl(get_patch_stage_out_struct_type()), "* ", patch_output_buffer_var_name,
11586 " [[buffer(", convert_to_string(msl_options.shader_patch_output_buffer_index), ")]]");
Chip Daviseb89c3a2019-02-03 23:58:46 -060011587 }
11588 if (!ep_args.empty())
11589 ep_args += ", ";
11590 ep_args += join("device ", get_tess_factor_struct_name(), "* ", tess_factor_buffer_var_name, " [[buffer(",
11591 convert_to_string(msl_options.shader_tess_factor_buffer_index), ")]]");
Hans-Kristian Arntzenad3e1582021-01-05 13:25:50 +010011592
11593 // Initializer for tess factors must be handled specially since it's never declared as a normal variable.
11594 uint32_t outer_factor_initializer_id = 0;
11595 uint32_t inner_factor_initializer_id = 0;
11596 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
11597 if (!has_decoration(var.self, DecorationBuiltIn) || var.storage != StorageClassOutput || !var.initializer)
11598 return;
11599
11600 BuiltIn builtin = BuiltIn(get_decoration(var.self, DecorationBuiltIn));
11601 if (builtin == BuiltInTessLevelInner)
11602 inner_factor_initializer_id = var.initializer;
11603 else if (builtin == BuiltInTessLevelOuter)
11604 outer_factor_initializer_id = var.initializer;
11605 });
11606
11607 const SPIRConstant *c = nullptr;
11608
11609 if (outer_factor_initializer_id && (c = maybe_get<SPIRConstant>(outer_factor_initializer_id)))
11610 {
11611 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
Hans-Kristian Arntzenefed4c92021-01-06 10:39:39 +010011612 entry_func.fixup_hooks_in.push_back([=]() {
11613 uint32_t components = get_execution_mode_bitset().get(ExecutionModeTriangles) ? 3 : 4;
11614 for (uint32_t i = 0; i < components; i++)
11615 {
11616 statement(builtin_to_glsl(BuiltInTessLevelOuter, StorageClassOutput), "[", i, "] = ",
11617 "half(", to_expression(c->subconstants[i]), ");");
11618 }
11619 });
Hans-Kristian Arntzenad3e1582021-01-05 13:25:50 +010011620 }
11621
11622 if (inner_factor_initializer_id && (c = maybe_get<SPIRConstant>(inner_factor_initializer_id)))
11623 {
11624 auto &entry_func = get<SPIRFunction>(ir.default_entry_point);
11625 if (get_execution_mode_bitset().get(ExecutionModeTriangles))
11626 {
11627 entry_func.fixup_hooks_in.push_back([=]() {
11628 statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), " = ", "half(",
11629 to_expression(c->subconstants[0]), ");");
11630 });
11631 }
11632 else
11633 {
11634 entry_func.fixup_hooks_in.push_back([=]() {
Hans-Kristian Arntzenefed4c92021-01-06 10:39:39 +010011635 for (uint32_t i = 0; i < 2; i++)
11636 {
11637 statement(builtin_to_glsl(BuiltInTessLevelInner, StorageClassOutput), "[", i, "] = ",
11638 "half(", to_expression(c->subconstants[i]), ");");
11639 }
Hans-Kristian Arntzenad3e1582021-01-05 13:25:50 +010011640 });
11641 }
11642 }
11643
Chip Daviseb89c3a2019-02-03 23:58:46 -060011644 if (stage_in_var_id)
11645 {
11646 if (!ep_args.empty())
11647 ep_args += ", ";
Chip Davis688c5fc2020-02-20 21:38:28 -060011648 if (msl_options.multi_patch_workgroup)
11649 {
11650 ep_args += join("device ", type_to_glsl(get_stage_in_struct_type()), "* ", input_buffer_var_name,
11651 " [[buffer(", convert_to_string(msl_options.shader_input_buffer_index), ")]]");
11652 }
11653 else
11654 {
11655 ep_args += join("threadgroup ", type_to_glsl(get_stage_in_struct_type()), "* ", input_wg_var_name,
11656 " [[threadgroup(", convert_to_string(msl_options.shader_input_wg_index), ")]]");
11657 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060011658 }
11659 }
Chip Davisc51e5b72019-01-08 16:33:32 -060011660 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011661}
11662
11663string CompilerMSL::entry_point_args_argument_buffer(bool append_comma)
11664{
11665 string ep_args = entry_point_arg_stage_in();
Hans-Kristian Arntzen048f2382019-06-24 10:45:13 +020011666 Bitset claimed_bindings;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011667
11668 for (uint32_t i = 0; i < kMaxArgumentBuffers; i++)
11669 {
11670 uint32_t id = argument_buffer_ids[i];
11671 if (id == 0)
11672 continue;
11673
11674 add_resource_name(id);
11675 auto &var = get<SPIRVariable>(id);
11676 auto &type = get_variable_data_type(var);
11677
11678 if (!ep_args.empty())
11679 ep_args += ", ";
11680
Hans-Kristian Arntzen048f2382019-06-24 10:45:13 +020011681 // Check if the argument buffer binding itself has been remapped.
11682 uint32_t buffer_binding;
11683 auto itr = resource_bindings.find({ get_entry_point().model, i, kArgumentBufferBinding });
11684 if (itr != end(resource_bindings))
11685 {
11686 buffer_binding = itr->second.first.msl_buffer;
11687 itr->second.second = true;
11688 }
11689 else
11690 {
11691 // As a fallback, directly map desc set <-> binding.
11692 // If that was taken, take the next buffer binding.
11693 if (claimed_bindings.get(i))
11694 buffer_binding = next_metal_resource_index_buffer;
11695 else
11696 buffer_binding = i;
11697 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011698
Hans-Kristian Arntzen048f2382019-06-24 10:45:13 +020011699 claimed_bindings.set(buffer_binding);
11700
Chip Davis058f1a02019-07-10 11:17:40 -050011701 ep_args += get_argument_address_space(var) + " " + type_to_glsl(type) + "& " + to_restrict(id) + to_name(id);
Hans-Kristian Arntzen048f2382019-06-24 10:45:13 +020011702 ep_args += " [[buffer(" + convert_to_string(buffer_binding) + ")]]";
11703
11704 next_metal_resource_index_buffer = max(next_metal_resource_index_buffer, buffer_binding + 1);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011705 }
11706
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010011707 entry_point_args_discrete_descriptors(ep_args);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011708 entry_point_args_builtin(ep_args);
11709
11710 if (!ep_args.empty() && append_comma)
11711 ep_args += ", ";
11712
11713 return ep_args;
11714}
11715
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020011716const MSLConstexprSampler *CompilerMSL::find_constexpr_sampler(uint32_t id) const
11717{
11718 // Try by ID.
11719 {
11720 auto itr = constexpr_samplers_by_id.find(id);
11721 if (itr != end(constexpr_samplers_by_id))
11722 return &itr->second;
11723 }
11724
11725 // Try by binding.
11726 {
11727 uint32_t desc_set = get_decoration(id, DecorationDescriptorSet);
11728 uint32_t binding = get_decoration(id, DecorationBinding);
11729
11730 auto itr = constexpr_samplers_by_binding.find({ desc_set, binding });
11731 if (itr != end(constexpr_samplers_by_binding))
11732 return &itr->second;
11733 }
11734
11735 return nullptr;
11736}
11737
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010011738void CompilerMSL::entry_point_args_discrete_descriptors(string &ep_args)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011739{
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011740 // Output resources, sorted by resource index & type
11741 // We need to sort to work around a bug on macOS 10.13 with NVidia drivers where switching between shaders
11742 // with different order of buffers can result in issues with buffer assignments inside the driver.
11743 struct Resource
11744 {
11745 SPIRVariable *var;
11746 string name;
11747 SPIRType::BaseType basetype;
11748 uint32_t index;
Chip Davis39dce882019-08-02 15:11:19 -050011749 uint32_t plane;
Lukas Hermannsa9f3c982019-09-13 14:03:02 -040011750 uint32_t secondary_index;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011751 };
11752
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020011753 SmallVector<Resource> resources;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011754
Chip Davis10381702019-09-04 13:57:17 -050011755 ir.for_each_typed_id<SPIRVariable>([&](uint32_t var_id, SPIRVariable &var) {
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011756 if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
11757 var.storage == StorageClassPushConstant || var.storage == StorageClassStorageBuffer) &&
11758 !is_hidden_variable(var))
11759 {
11760 auto &type = get_variable_data_type(var);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011761
Hans-Kristian Arntzen893a0112021-01-07 15:00:45 +010011762 if (is_supported_argument_buffer_type(type) && var.storage != StorageClassPushConstant)
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010011763 {
11764 uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
11765 if (descriptor_set_is_argument_buffer(desc_set))
11766 return;
11767 }
11768
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020011769 const MSLConstexprSampler *constexpr_sampler = nullptr;
11770 if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
11771 {
11772 constexpr_sampler = find_constexpr_sampler(var_id);
11773 if (constexpr_sampler)
11774 {
11775 // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
11776 constexpr_samplers_by_id[var_id] = *constexpr_sampler;
11777 }
11778 }
11779
Lukas Hermanns50ac6862019-09-18 14:03:54 -040011780 // Emulate texture2D atomic operations
Lukas Hermannsa9f3c982019-09-13 14:03:02 -040011781 uint32_t secondary_index = 0;
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020011782 if (atomic_image_vars.count(var.self))
Lukas Hermannsa9f3c982019-09-13 14:03:02 -040011783 {
11784 secondary_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
11785 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011786
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011787 if (type.basetype == SPIRType::SampledImage)
11788 {
11789 add_resource_name(var_id);
Chip Davis39dce882019-08-02 15:11:19 -050011790
11791 uint32_t plane_count = 1;
11792 if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
11793 plane_count = constexpr_sampler->planes;
11794
11795 for (uint32_t i = 0; i < plane_count; i++)
11796 resources.push_back({ &var, to_name(var_id), SPIRType::Image,
Lukas Hermannsa9f3c982019-09-13 14:03:02 -040011797 get_metal_resource_index(var, SPIRType::Image, i), i, secondary_index });
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011798
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020011799 if (type.image.dim != DimBuffer && !constexpr_sampler)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011800 {
11801 resources.push_back({ &var, to_sampler_expression(var_id), SPIRType::Sampler,
Lukas Hermannsa9f3c982019-09-13 14:03:02 -040011802 get_metal_resource_index(var, SPIRType::Sampler), 0, 0 });
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011803 }
11804 }
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020011805 else if (!constexpr_sampler)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011806 {
11807 // constexpr samplers are not declared as resources.
11808 add_resource_name(var_id);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011809 resources.push_back({ &var, to_name(var_id), type.basetype,
11810 get_metal_resource_index(var, type.basetype), 0, secondary_index });
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011811 }
11812 }
11813 });
11814
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010011815 sort(resources.begin(), resources.end(), [](const Resource &lhs, const Resource &rhs) {
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011816 return tie(lhs.basetype, lhs.index) < tie(rhs.basetype, rhs.index);
11817 });
11818
11819 for (auto &r : resources)
11820 {
11821 auto &var = *r.var;
11822 auto &type = get_variable_data_type(var);
11823
11824 uint32_t var_id = var.self;
11825
11826 switch (r.basetype)
11827 {
11828 case SPIRType::Struct:
11829 {
11830 auto &m = ir.meta[type.self];
11831 if (m.members.size() == 0)
11832 break;
11833 if (!type.array.empty())
11834 {
11835 if (type.array.size() > 1)
11836 SPIRV_CROSS_THROW("Arrays of arrays of buffers are not supported.");
11837
11838 // Metal doesn't directly support this, so we must expand the
11839 // array. We'll declare a local array to hold these elements
11840 // later.
11841 uint32_t array_size = to_array_size_literal(type);
11842
11843 if (array_size == 0)
11844 SPIRV_CROSS_THROW("Unsized arrays of buffers are not supported in MSL.");
11845
Lukas Hermanns50ac6862019-09-18 14:03:54 -040011846 // Allow Metal to use the array<T> template to make arrays a value type
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010011847 is_using_builtin_array = true;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011848 buffer_arrays.push_back(var_id);
11849 for (uint32_t i = 0; i < array_size; ++i)
11850 {
11851 if (!ep_args.empty())
11852 ep_args += ", ";
Chip Davis058f1a02019-07-10 11:17:40 -050011853 ep_args += get_argument_address_space(var) + " " + type_to_glsl(type) + "* " + to_restrict(var_id) +
11854 r.name + "_" + convert_to_string(i);
Chip Davis2eff4202019-08-04 00:07:20 -050011855 ep_args += " [[buffer(" + convert_to_string(r.index + i) + ")";
11856 if (interlocked_resources.count(var_id))
11857 ep_args += ", raster_order_group(0)";
11858 ep_args += "]]";
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011859 }
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010011860 is_using_builtin_array = false;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011861 }
11862 else
11863 {
11864 if (!ep_args.empty())
11865 ep_args += ", ";
Chip Davis058f1a02019-07-10 11:17:40 -050011866 ep_args +=
11867 get_argument_address_space(var) + " " + type_to_glsl(type) + "& " + to_restrict(var_id) + r.name;
Chip Davis2eff4202019-08-04 00:07:20 -050011868 ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
11869 if (interlocked_resources.count(var_id))
11870 ep_args += ", raster_order_group(0)";
11871 ep_args += "]]";
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011872 }
11873 break;
11874 }
11875 case SPIRType::Sampler:
11876 if (!ep_args.empty())
11877 ep_args += ", ";
Bill Hollingsb7b0e802020-10-29 18:50:42 -040011878 ep_args += sampler_type(type, var_id) + " " + r.name;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011879 ep_args += " [[sampler(" + convert_to_string(r.index) + ")]]";
11880 break;
11881 case SPIRType::Image:
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040011882 {
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011883 if (!ep_args.empty())
11884 ep_args += ", ";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011885
11886 // Use Metal's native frame-buffer fetch API for subpass inputs.
11887 const auto &basetype = get<SPIRType>(var.basetype);
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020011888 if (!type_is_msl_framebuffer_fetch(basetype))
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011889 {
Mark Satterthwaite97a66ff2019-08-14 10:48:47 -040011890 ep_args += image_type_glsl(type, var_id) + " " + r.name;
Lukas Hermanns37df7402019-09-20 09:28:46 -040011891 if (r.plane > 0)
11892 ep_args += join(plane_name_suffix, r.plane);
11893 ep_args += " [[texture(" + convert_to_string(r.index) + ")";
11894 if (interlocked_resources.count(var_id))
11895 ep_args += ", raster_order_group(0)";
11896 ep_args += "]]";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011897 }
11898 else
11899 {
Chip Davisc20d5942020-10-27 21:42:33 -050011900 if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 3))
11901 SPIRV_CROSS_THROW("Framebuffer fetch on Mac is not supported before MSL 2.3.");
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020011902 ep_args += image_type_glsl(type, var_id) + " " + r.name;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011903 ep_args += " [[color(" + convert_to_string(r.index) + ")]]";
11904 }
11905
11906 // Emulate texture2D atomic operations
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020011907 if (atomic_image_vars.count(var.self))
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011908 {
11909 ep_args += ", device atomic_" + type_to_glsl(get<SPIRType>(basetype.image.type), 0);
11910 ep_args += "* " + r.name + "_atomic";
Chip Davis7a5d0d62020-10-13 11:41:29 -050011911 ep_args += " [[buffer(" + convert_to_string(r.secondary_index) + ")";
11912 if (interlocked_resources.count(var_id))
11913 ep_args += ", raster_order_group(0)";
11914 ep_args += "]]";
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011915 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011916 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040011917 }
丛越597f29d2021-10-19 18:45:10 +080011918 case SPIRType::AccelerationStructure:
11919 ep_args += ", " + type_to_glsl(type, var_id) + " " + r.name;
11920 ep_args += " [[buffer(" + convert_to_string(r.index) + ")]]";
11921 break;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011922 default:
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020011923 if (!ep_args.empty())
11924 ep_args += ", ";
Chip Davisfb5ee4c2019-07-22 13:08:04 -050011925 if (!type.pointer)
11926 ep_args += get_type_address_space(get<SPIRType>(var.basetype), var_id) + " " +
11927 type_to_glsl(type, var_id) + "& " + r.name;
11928 else
11929 ep_args += type_to_glsl(type, var_id) + " " + r.name;
Chip Davis2eff4202019-08-04 00:07:20 -050011930 ep_args += " [[buffer(" + convert_to_string(r.index) + ")";
11931 if (interlocked_resources.count(var_id))
11932 ep_args += ", raster_order_group(0)";
11933 ep_args += "]]";
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011934 break;
11935 }
11936 }
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010011937}
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011938
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010011939// Returns a string containing a comma-delimited list of args for the entry point function
11940// This is the "classic" method of MSL 1 when we don't have argument buffer support.
11941string CompilerMSL::entry_point_args_classic(bool append_comma)
11942{
11943 string ep_args = entry_point_arg_stage_in();
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010011944 entry_point_args_discrete_descriptors(ep_args);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010011945 entry_point_args_builtin(ep_args);
Chip Davisc51e5b72019-01-08 16:33:32 -060011946
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011947 if (!ep_args.empty() && append_comma)
11948 ep_args += ", ";
Bill Hollings103aabf2016-04-06 17:42:27 -040011949
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020011950 return ep_args;
Bill Hollings103aabf2016-04-06 17:42:27 -040011951}
11952
Chip Davisf500d2f2019-01-16 17:52:53 -060011953void CompilerMSL::fix_up_shader_inputs_outputs()
11954{
Chip Davis688c5fc2020-02-20 21:38:28 -060011955 auto &entry_func = this->get<SPIRFunction>(ir.default_entry_point);
11956
11957 // Emit a guard to ensure we don't execute beyond the last vertex.
11958 // Vertex shaders shouldn't have the problems with barriers in non-uniform control flow that
11959 // tessellation control shaders do, so early returns should be OK. We may need to revisit this
11960 // if it ever becomes possible to use barriers from a vertex shader.
11961 if (get_execution_model() == ExecutionModelVertex && msl_options.vertex_for_tessellation)
11962 {
11963 entry_func.fixup_hooks_in.push_back([this]() {
11964 statement("if (any(", to_expression(builtin_invocation_id_id),
11965 " >= ", to_expression(builtin_stage_input_size_id), "))");
11966 statement(" return;");
11967 });
11968 }
11969
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020011970 // Look for sampled images and buffer. Add hooks to set up the swizzle constants or array lengths.
Chip Davisf500d2f2019-01-16 17:52:53 -060011971 ir.for_each_typed_id<SPIRVariable>([&](uint32_t, SPIRVariable &var) {
11972 auto &type = get_variable_data_type(var);
Chip Davisf500d2f2019-01-16 17:52:53 -060011973 uint32_t var_id = var.self;
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020011974 bool ssbo = has_decoration(type.self, DecorationBufferBlock);
Chip Davisf500d2f2019-01-16 17:52:53 -060011975
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020011976 if (var.storage == StorageClassUniformConstant && !is_hidden_variable(var))
Chip Davisf500d2f2019-01-16 17:52:53 -060011977 {
11978 if (msl_options.swizzle_texture_samples && has_sampled_images && is_sampled_image_type(type))
11979 {
Hans-Kristian Arntzen97d39dc2019-05-09 11:25:45 +020011980 entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
Hans-Kristian Arntzen97d39dc2019-05-09 11:25:45 +020011981 bool is_array_type = !type.array.empty();
11982
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020011983 uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
11984 if (descriptor_set_is_argument_buffer(desc_set))
11985 {
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020011986 statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020011987 is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
11988 ".spvSwizzleConstants", "[",
11989 convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
11990 }
11991 else
11992 {
11993 // If we have an array of images, we need to be able to index into it, so take a pointer instead.
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020011994 statement("constant uint", is_array_type ? "* " : "& ", to_swizzle_expression(var_id),
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020011995 is_array_type ? " = &" : " = ", to_name(swizzle_buffer_id), "[",
11996 convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
11997 }
Chip Davisf500d2f2019-01-16 17:52:53 -060011998 });
11999 }
12000 }
Hans-Kristian Arntzenb3094cd2019-05-27 16:54:13 +020012001 else if ((var.storage == StorageClassStorageBuffer || (var.storage == StorageClassUniform && ssbo)) &&
12002 !is_hidden_variable(var))
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020012003 {
12004 if (buffers_requiring_array_length.count(var.self))
12005 {
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020012006 entry_func.fixup_hooks_in.push_back([this, &type, &var, var_id]() {
12007 bool is_array_type = !type.array.empty();
12008
12009 uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
12010 if (descriptor_set_is_argument_buffer(desc_set))
12011 {
12012 statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
12013 is_array_type ? " = &" : " = ", to_name(argument_buffer_ids[desc_set]),
12014 ".spvBufferSizeConstants", "[",
12015 convert_to_string(get_metal_resource_index(var, SPIRType::Image)), "];");
12016 }
12017 else
12018 {
12019 // If we have an array of images, we need to be able to index into it, so take a pointer instead.
12020 statement("constant uint", is_array_type ? "* " : "& ", to_buffer_size_expression(var_id),
12021 is_array_type ? " = &" : " = ", to_name(buffer_size_buffer_id), "[",
12022 convert_to_string(get_metal_resource_index(var, type.basetype)), "];");
12023 }
12024 });
12025 }
12026 }
Chip Davisf500d2f2019-01-16 17:52:53 -060012027 });
12028
12029 // Builtin variables
Chip Davis688c5fc2020-02-20 21:38:28 -060012030 ir.for_each_typed_id<SPIRVariable>([this, &entry_func](uint32_t, SPIRVariable &var) {
Chip Davisf500d2f2019-01-16 17:52:53 -060012031 uint32_t var_id = var.self;
12032 BuiltIn bi_type = ir.meta[var_id].decoration.builtin_type;
12033
Hans-Kristian Arntzenfa76d012021-01-07 10:28:06 +010012034 if (var.storage != StorageClassInput && var.storage != StorageClassOutput)
12035 return;
12036 if (!interface_variable_exists_in_entry_point(var.self))
12037 return;
12038
comexc80cbde2020-11-25 12:43:01 -050012039 if (var.storage == StorageClassInput && is_builtin_variable(var) && active_input_builtins.get(bi_type))
Chip Davisf500d2f2019-01-16 17:52:53 -060012040 {
Chip Davisf500d2f2019-01-16 17:52:53 -060012041 switch (bi_type)
12042 {
12043 case BuiltInSamplePosition:
12044 entry_func.fixup_hooks_in.push_back([=]() {
12045 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = get_sample_position(",
12046 to_expression(builtin_sample_id_id), ");");
12047 });
12048 break;
Chip Davisfd738e32020-11-20 15:41:46 -060012049 case BuiltInFragCoord:
12050 if (is_sample_rate())
12051 {
12052 entry_func.fixup_hooks_in.push_back([=]() {
12053 statement(to_expression(var_id), ".xy += get_sample_position(",
12054 to_expression(builtin_sample_id_id), ") - 0.5;");
12055 });
12056 }
12057 break;
Chip Davisf500d2f2019-01-16 17:52:53 -060012058 case BuiltInHelperInvocation:
Chip Davis88e25e62020-11-14 01:57:11 -060012059 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
12060 SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.3 on iOS.");
Chip Davisf500d2f2019-01-16 17:52:53 -060012061 else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
12062 SPIRV_CROSS_THROW("simd_is_helper_thread() requires version 2.1 on macOS.");
12063
12064 entry_func.fixup_hooks_in.push_back([=]() {
12065 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = simd_is_helper_thread();");
12066 });
12067 break;
Chip Davis688c5fc2020-02-20 21:38:28 -060012068 case BuiltInInvocationId:
12069 // This is direct-mapped without multi-patch workgroups.
12070 if (get_execution_model() != ExecutionModelTessellationControl || !msl_options.multi_patch_workgroup)
12071 break;
12072
12073 entry_func.fixup_hooks_in.push_back([=]() {
12074 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12075 to_expression(builtin_invocation_id_id), ".x % ", this->get_entry_point().output_vertices,
12076 ";");
12077 });
12078 break;
12079 case BuiltInPrimitiveId:
12080 // This is natively supported by fragment and tessellation evaluation shaders.
12081 // In tessellation control shaders, this is direct-mapped without multi-patch workgroups.
12082 if (get_execution_model() != ExecutionModelTessellationControl || !msl_options.multi_patch_workgroup)
12083 break;
12084
12085 entry_func.fixup_hooks_in.push_back([=]() {
12086 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = min(",
12087 to_expression(builtin_invocation_id_id), ".x / ", this->get_entry_point().output_vertices,
Lukas Taparauskas72a2ec42021-04-29 21:01:26 +030012088 ", spvIndirectParams[1] - 1);");
Chip Davis688c5fc2020-02-20 21:38:28 -060012089 });
12090 break;
Chip Daviseb89c3a2019-02-03 23:58:46 -060012091 case BuiltInPatchVertices:
Chip Davise75add42019-02-05 18:13:26 -060012092 if (get_execution_model() == ExecutionModelTessellationEvaluation)
12093 entry_func.fixup_hooks_in.push_back([=]() {
12094 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12095 to_expression(patch_stage_in_var_id), ".gl_in.size();");
12096 });
12097 else
12098 entry_func.fixup_hooks_in.push_back([=]() {
12099 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = spvIndirectParams[0];");
12100 });
Chip Daviseb89c3a2019-02-03 23:58:46 -060012101 break;
Chip Davis41d94242019-02-05 23:47:50 -060012102 case BuiltInTessCoord:
Hans-Kristian Arntzenbe333e02022-01-05 13:31:51 +010012103 if (get_entry_point().flags.get(ExecutionModeQuads))
12104 {
12105 // The entry point will only have a float2 TessCoord variable.
12106 // Pad to float3.
12107 entry_func.fixup_hooks_in.push_back([=]() {
12108 auto name = builtin_to_glsl(BuiltInTessCoord, StorageClassInput);
12109 statement("float3 " + name + " = float3(" + name + "In.x, " + name + "In.y, 0.0);");
12110 });
12111 }
12112
Chip Davis285ca4c2019-02-20 14:07:18 -060012113 // Emit a fixup to account for the shifted domain. Don't do this for triangles;
12114 // MoltenVK will just reverse the winding order instead.
12115 if (msl_options.tess_domain_origin_lower_left && !get_entry_point().flags.get(ExecutionModeTriangles))
Chip Davis41d94242019-02-05 23:47:50 -060012116 {
12117 string tc = to_expression(var_id);
Chip Davis285ca4c2019-02-20 14:07:18 -060012118 entry_func.fixup_hooks_in.push_back([=]() { statement(tc, ".y = 1.0 - ", tc, ".y;"); });
Chip Davis41d94242019-02-05 23:47:50 -060012119 }
12120 break;
Chip Davis68908352020-11-18 23:16:46 -060012121 case BuiltInSubgroupId:
12122 if (!msl_options.emulate_subgroups)
Chip Davis31b6c932019-05-31 13:42:36 -050012123 break;
Chip Davis68908352020-11-18 23:16:46 -060012124 // For subgroup emulation, this is the same as the local invocation index.
Chip Davis31b6c932019-05-31 13:42:36 -050012125 entry_func.fixup_hooks_in.push_back([=]() {
Chip Davis68908352020-11-18 23:16:46 -060012126 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12127 to_expression(builtin_local_invocation_index_id), ";");
Chip Davis31b6c932019-05-31 13:42:36 -050012128 });
12129 break;
Chip Davis68908352020-11-18 23:16:46 -060012130 case BuiltInNumSubgroups:
12131 if (!msl_options.emulate_subgroups)
Chip Davis31b6c932019-05-31 13:42:36 -050012132 break;
Chip Davis68908352020-11-18 23:16:46 -060012133 // For subgroup emulation, this is the same as the workgroup size.
12134 entry_func.fixup_hooks_in.push_back([=]() {
12135 auto &type = expression_type(builtin_workgroup_size_id);
12136 string size_expr = to_expression(builtin_workgroup_size_id);
12137 if (type.vecsize >= 3)
12138 size_expr = join(size_expr, ".x * ", size_expr, ".y * ", size_expr, ".z");
12139 else if (type.vecsize == 2)
12140 size_expr = join(size_expr, ".x * ", size_expr, ".y");
12141 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", size_expr, ";");
12142 });
12143 break;
12144 case BuiltInSubgroupLocalInvocationId:
12145 if (!msl_options.emulate_subgroups)
Chip Davis31b6c932019-05-31 13:42:36 -050012146 break;
Chip Davis68908352020-11-18 23:16:46 -060012147 // For subgroup emulation, assume subgroups of size 1.
Chip Davis31b6c932019-05-31 13:42:36 -050012148 entry_func.fixup_hooks_in.push_back(
Chip Davis68908352020-11-18 23:16:46 -060012149 [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;"); });
12150 break;
12151 case BuiltInSubgroupSize:
12152 if (msl_options.emulate_subgroups)
12153 {
12154 // For subgroup emulation, assume subgroups of size 1.
12155 entry_func.fixup_hooks_in.push_back(
12156 [=]() { statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = 1;"); });
12157 }
12158 else if (msl_options.fixed_subgroup_size != 0)
12159 {
12160 entry_func.fixup_hooks_in.push_back([=]() {
12161 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12162 msl_options.fixed_subgroup_size, ";");
12163 });
12164 }
Chip Davis31b6c932019-05-31 13:42:36 -050012165 break;
Chip Davis9d941572019-05-15 16:03:30 -050012166 case BuiltInSubgroupEqMask:
Chip Davis68908352020-11-18 23:16:46 -060012167 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
12168 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
Chip Davis9d941572019-05-15 16:03:30 -050012169 if (!msl_options.supports_msl_version(2, 1))
12170 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
12171 entry_func.fixup_hooks_in.push_back([=]() {
Chip Davis68908352020-11-18 23:16:46 -060012172 if (msl_options.is_ios())
12173 {
12174 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", "uint4(1 << ",
12175 to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
12176 }
12177 else
12178 {
12179 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12180 to_expression(builtin_subgroup_invocation_id_id), " >= 32 ? uint4(0, (1 << (",
12181 to_expression(builtin_subgroup_invocation_id_id), " - 32)), uint2(0)) : uint4(1 << ",
12182 to_expression(builtin_subgroup_invocation_id_id), ", uint3(0));");
12183 }
Chip Davis9d941572019-05-15 16:03:30 -050012184 });
12185 break;
12186 case BuiltInSubgroupGeMask:
Chip Davis68908352020-11-18 23:16:46 -060012187 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
12188 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
Chip Davis9d941572019-05-15 16:03:30 -050012189 if (!msl_options.supports_msl_version(2, 1))
12190 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
Chip Davis68908352020-11-18 23:16:46 -060012191 if (msl_options.fixed_subgroup_size != 0)
12192 add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
Chip Davis9d941572019-05-15 16:03:30 -050012193 entry_func.fixup_hooks_in.push_back([=]() {
12194 // Case where index < 32, size < 32:
Chip Davis6ccb9022020-10-20 21:58:07 -050012195 // mask0 = bfi(0, 0xFFFFFFFF, index, size - index);
12196 // mask1 = bfi(0, 0xFFFFFFFF, 0, 0); // Gives 0
Chip Davis9d941572019-05-15 16:03:30 -050012197 // Case where index < 32 but size >= 32:
Chip Davis6ccb9022020-10-20 21:58:07 -050012198 // mask0 = bfi(0, 0xFFFFFFFF, index, 32 - index);
12199 // mask1 = bfi(0, 0xFFFFFFFF, 0, size - 32);
Chip Davis9d941572019-05-15 16:03:30 -050012200 // Case where index >= 32:
Chip Davis6ccb9022020-10-20 21:58:07 -050012201 // mask0 = bfi(0, 0xFFFFFFFF, 32, 0); // Gives 0
12202 // mask1 = bfi(0, 0xFFFFFFFF, index - 32, size - index);
Chip Davis9d941572019-05-15 16:03:30 -050012203 // This is expressed without branches to avoid divergent
12204 // control flow--hence the complicated min/max expressions.
12205 // This is further complicated by the fact that if you attempt
Chip Davis6ccb9022020-10-20 21:58:07 -050012206 // to bfi/bfe out-of-bounds on Metal, undefined behavior is the
Chip Davis9d941572019-05-15 16:03:30 -050012207 // result.
Chip Davis68908352020-11-18 23:16:46 -060012208 if (msl_options.fixed_subgroup_size > 32)
12209 {
12210 // Don't use the subgroup size variable with fixed subgroup sizes,
12211 // since the variables could be defined in the wrong order.
12212 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12213 " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
12214 to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(32 - (int)",
12215 to_expression(builtin_subgroup_invocation_id_id),
12216 ", 0)), insert_bits(0u, 0xFFFFFFFF,"
12217 " (uint)max((int)",
12218 to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), ",
12219 msl_options.fixed_subgroup_size, " - max(",
12220 to_expression(builtin_subgroup_invocation_id_id),
Chip Davis1e67b212020-11-23 12:29:47 -060012221 ", 32u)), uint2(0));");
Chip Davis68908352020-11-18 23:16:46 -060012222 }
12223 else if (msl_options.fixed_subgroup_size != 0)
12224 {
12225 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12226 " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
12227 to_expression(builtin_subgroup_invocation_id_id), ", ",
12228 msl_options.fixed_subgroup_size, " - ",
12229 to_expression(builtin_subgroup_invocation_id_id),
Chip Davis1e67b212020-11-23 12:29:47 -060012230 "), uint3(0));");
Chip Davis68908352020-11-18 23:16:46 -060012231 }
12232 else if (msl_options.is_ios())
12233 {
12234 // On iOS, the SIMD-group size will currently never exceed 32.
12235 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12236 " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
12237 to_expression(builtin_subgroup_invocation_id_id), ", ",
12238 to_expression(builtin_subgroup_size_id), " - ",
12239 to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
12240 }
12241 else
12242 {
12243 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12244 " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
12245 to_expression(builtin_subgroup_invocation_id_id), ", 32u), (uint)max(min((int)",
12246 to_expression(builtin_subgroup_size_id), ", 32) - (int)",
12247 to_expression(builtin_subgroup_invocation_id_id),
12248 ", 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
12249 to_expression(builtin_subgroup_invocation_id_id), " - 32, 0), (uint)max((int)",
12250 to_expression(builtin_subgroup_size_id), " - (int)max(",
12251 to_expression(builtin_subgroup_invocation_id_id), ", 32u), 0)), uint2(0));");
12252 }
Chip Davis9d941572019-05-15 16:03:30 -050012253 });
12254 break;
12255 case BuiltInSubgroupGtMask:
Chip Davis68908352020-11-18 23:16:46 -060012256 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
12257 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
Chip Davis9d941572019-05-15 16:03:30 -050012258 if (!msl_options.supports_msl_version(2, 1))
12259 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
Chip Davis68908352020-11-18 23:16:46 -060012260 add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
Chip Davis9d941572019-05-15 16:03:30 -050012261 entry_func.fixup_hooks_in.push_back([=]() {
12262 // The same logic applies here, except now the index is one
12263 // more than the subgroup invocation ID.
Chip Davis68908352020-11-18 23:16:46 -060012264 if (msl_options.fixed_subgroup_size > 32)
12265 {
12266 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12267 " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
12268 to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(32 - (int)",
12269 to_expression(builtin_subgroup_invocation_id_id),
12270 " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
12271 to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), ",
12272 msl_options.fixed_subgroup_size, " - max(",
12273 to_expression(builtin_subgroup_invocation_id_id),
Chip Davis1e67b212020-11-23 12:29:47 -060012274 " + 1, 32u)), uint2(0));");
Chip Davis68908352020-11-18 23:16:46 -060012275 }
12276 else if (msl_options.fixed_subgroup_size != 0)
12277 {
12278 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12279 " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
12280 to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
12281 msl_options.fixed_subgroup_size, " - ",
12282 to_expression(builtin_subgroup_invocation_id_id),
Chip Davis1e67b212020-11-23 12:29:47 -060012283 " - 1), uint3(0));");
Chip Davis68908352020-11-18 23:16:46 -060012284 }
12285 else if (msl_options.is_ios())
12286 {
12287 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12288 " = uint4(insert_bits(0u, 0xFFFFFFFF, ",
12289 to_expression(builtin_subgroup_invocation_id_id), " + 1, ",
12290 to_expression(builtin_subgroup_size_id), " - ",
12291 to_expression(builtin_subgroup_invocation_id_id), " - 1), uint3(0));");
12292 }
12293 else
12294 {
12295 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12296 " = uint4(insert_bits(0u, 0xFFFFFFFF, min(",
12297 to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), (uint)max(min((int)",
12298 to_expression(builtin_subgroup_size_id), ", 32) - (int)",
12299 to_expression(builtin_subgroup_invocation_id_id),
12300 " - 1, 0)), insert_bits(0u, 0xFFFFFFFF, (uint)max((int)",
12301 to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0), (uint)max((int)",
12302 to_expression(builtin_subgroup_size_id), " - (int)max(",
12303 to_expression(builtin_subgroup_invocation_id_id), " + 1, 32u), 0)), uint2(0));");
12304 }
Chip Davis9d941572019-05-15 16:03:30 -050012305 });
12306 break;
12307 case BuiltInSubgroupLeMask:
Chip Davis68908352020-11-18 23:16:46 -060012308 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
12309 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
Chip Davis9d941572019-05-15 16:03:30 -050012310 if (!msl_options.supports_msl_version(2, 1))
12311 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
Chip Davis68908352020-11-18 23:16:46 -060012312 add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
Chip Davis9d941572019-05-15 16:03:30 -050012313 entry_func.fixup_hooks_in.push_back([=]() {
Chip Davis68908352020-11-18 23:16:46 -060012314 if (msl_options.is_ios())
12315 {
12316 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12317 " = uint4(extract_bits(0xFFFFFFFF, 0, ",
12318 to_expression(builtin_subgroup_invocation_id_id), " + 1), uint3(0));");
12319 }
12320 else
12321 {
12322 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12323 " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
12324 to_expression(builtin_subgroup_invocation_id_id),
12325 " + 1, 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
12326 to_expression(builtin_subgroup_invocation_id_id), " + 1 - 32, 0)), uint2(0));");
12327 }
Chip Davis9d941572019-05-15 16:03:30 -050012328 });
12329 break;
12330 case BuiltInSubgroupLtMask:
Chip Davis68908352020-11-18 23:16:46 -060012331 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 2))
12332 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.2 on iOS.");
Chip Davis9d941572019-05-15 16:03:30 -050012333 if (!msl_options.supports_msl_version(2, 1))
12334 SPIRV_CROSS_THROW("Subgroup ballot functionality requires Metal 2.1.");
Chip Davis68908352020-11-18 23:16:46 -060012335 add_spv_func_and_recompile(SPVFuncImplSubgroupBallot);
Chip Davis9d941572019-05-15 16:03:30 -050012336 entry_func.fixup_hooks_in.push_back([=]() {
Chip Davis68908352020-11-18 23:16:46 -060012337 if (msl_options.is_ios())
12338 {
12339 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12340 " = uint4(extract_bits(0xFFFFFFFF, 0, ",
12341 to_expression(builtin_subgroup_invocation_id_id), "), uint3(0));");
12342 }
12343 else
12344 {
12345 statement(builtin_type_decl(bi_type), " ", to_expression(var_id),
12346 " = uint4(extract_bits(0xFFFFFFFF, 0, min(",
12347 to_expression(builtin_subgroup_invocation_id_id),
12348 ", 32u)), extract_bits(0xFFFFFFFF, 0, (uint)max((int)",
12349 to_expression(builtin_subgroup_invocation_id_id), " - 32, 0)), uint2(0));");
12350 }
Chip Davis9d941572019-05-15 16:03:30 -050012351 });
12352 break;
Chip Davis7eecf5a2019-05-31 12:06:20 -050012353 case BuiltInViewIndex:
12354 if (!msl_options.multiview)
12355 {
12356 // According to the Vulkan spec, when not running under a multiview
12357 // render pass, ViewIndex is 0.
12358 entry_func.fixup_hooks_in.push_back([=]() {
12359 statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = 0;");
12360 });
12361 }
Chip Davis6a585542019-07-12 21:50:50 -050012362 else if (msl_options.view_index_from_device_index)
12363 {
12364 // In this case, we take the view index from that of the device we're running on.
12365 entry_func.fixup_hooks_in.push_back([=]() {
12366 statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12367 msl_options.device_index, ";");
12368 });
12369 // We actually don't want to set the render_target_array_index here.
12370 // Since every physical device is rendering a different view,
12371 // there's no need for layered rendering here.
12372 }
Chip Daviscab73352020-08-23 16:44:41 -050012373 else if (!msl_options.multiview_layered_rendering)
12374 {
12375 // In this case, the views are rendered one at a time. The view index, then,
12376 // is just the first part of the "view mask".
12377 entry_func.fixup_hooks_in.push_back([=]() {
12378 statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12379 to_expression(view_mask_buffer_id), "[0];");
12380 });
12381 }
Chip Davis7eecf5a2019-05-31 12:06:20 -050012382 else if (get_execution_model() == ExecutionModelFragment)
12383 {
12384 // Because we adjusted the view index in the vertex shader, we have to
12385 // adjust it back here.
12386 entry_func.fixup_hooks_in.push_back([=]() {
12387 statement(to_expression(var_id), " += ", to_expression(view_mask_buffer_id), "[0];");
12388 });
12389 }
12390 else if (get_execution_model() == ExecutionModelVertex)
12391 {
12392 // Metal provides no special support for multiview, so we smuggle
12393 // the view index in the instance index.
12394 entry_func.fixup_hooks_in.push_back([=]() {
12395 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
Chip Davis53080ec2020-08-07 17:46:28 -050012396 to_expression(view_mask_buffer_id), "[0] + (", to_expression(builtin_instance_idx_id),
12397 " - ", to_expression(builtin_base_instance_id), ") % ",
12398 to_expression(view_mask_buffer_id), "[1];");
12399 statement(to_expression(builtin_instance_idx_id), " = (",
12400 to_expression(builtin_instance_idx_id), " - ",
12401 to_expression(builtin_base_instance_id), ") / ", to_expression(view_mask_buffer_id),
12402 "[1] + ", to_expression(builtin_base_instance_id), ";");
Chip Davis7eecf5a2019-05-31 12:06:20 -050012403 });
12404 // In addition to setting the variable itself, we also need to
12405 // set the render_target_array_index with it on output. We have to
12406 // offset this by the base view index, because Metal isn't in on
12407 // our little game here.
12408 entry_func.fixup_hooks_out.push_back([=]() {
12409 statement(to_expression(builtin_layer_id), " = ", to_expression(var_id), " - ",
12410 to_expression(view_mask_buffer_id), "[0];");
12411 });
12412 }
12413 break;
Chip Davis6a585542019-07-12 21:50:50 -050012414 case BuiltInDeviceIndex:
12415 // Metal pipelines belong to the devices which create them, so we'll
12416 // need to create a MTLPipelineState for every MTLDevice in a grouped
12417 // VkDevice. We can assume, then, that the device index is constant.
12418 entry_func.fixup_hooks_in.push_back([=]() {
12419 statement("const ", builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12420 msl_options.device_index, ";");
12421 });
12422 break;
Chip Davisfb5ee4c2019-07-22 13:08:04 -050012423 case BuiltInWorkgroupId:
12424 if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInWorkgroupId))
12425 break;
12426
12427 // The vkCmdDispatchBase() command lets the client set the base value
12428 // of WorkgroupId. Metal has no direct equivalent; we must make this
12429 // adjustment ourselves.
12430 entry_func.fixup_hooks_in.push_back([=]() {
12431 statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id), ";");
12432 });
12433 break;
12434 case BuiltInGlobalInvocationId:
12435 if (!msl_options.dispatch_base || !active_input_builtins.get(BuiltInGlobalInvocationId))
12436 break;
12437
12438 // GlobalInvocationId is defined as LocalInvocationId + WorkgroupId * WorkgroupSize.
12439 // This needs to be adjusted too.
12440 entry_func.fixup_hooks_in.push_back([=]() {
Hans-Kristian Arntzen3c03b552019-07-25 10:28:11 +020012441 auto &execution = this->get_entry_point();
Chip Davisfb5ee4c2019-07-22 13:08:04 -050012442 uint32_t workgroup_size_id = execution.workgroup_size.constant;
12443 if (workgroup_size_id)
12444 statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
12445 " * ", to_expression(workgroup_size_id), ";");
12446 else
12447 statement(to_expression(var_id), " += ", to_dereferenced_expression(builtin_dispatch_base_id),
12448 " * uint3(", execution.workgroup_size.x, ", ", execution.workgroup_size.y, ", ",
12449 execution.workgroup_size.z, ");");
12450 });
12451 break;
Chip Davis688c5fc2020-02-20 21:38:28 -060012452 case BuiltInVertexId:
12453 case BuiltInVertexIndex:
12454 // This is direct-mapped normally.
12455 if (!msl_options.vertex_for_tessellation)
12456 break;
12457
12458 entry_func.fixup_hooks_in.push_back([=]() {
12459 builtin_declaration = true;
12460 switch (msl_options.vertex_index_type)
12461 {
12462 case Options::IndexType::None:
12463 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12464 to_expression(builtin_invocation_id_id), ".x + ",
12465 to_expression(builtin_dispatch_base_id), ".x;");
12466 break;
12467 case Options::IndexType::UInt16:
12468 case Options::IndexType::UInt32:
12469 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ", index_buffer_var_name,
12470 "[", to_expression(builtin_invocation_id_id), ".x] + ",
12471 to_expression(builtin_dispatch_base_id), ".x;");
12472 break;
12473 }
12474 builtin_declaration = false;
12475 });
12476 break;
12477 case BuiltInBaseVertex:
12478 // This is direct-mapped normally.
12479 if (!msl_options.vertex_for_tessellation)
12480 break;
12481
12482 entry_func.fixup_hooks_in.push_back([=]() {
12483 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12484 to_expression(builtin_dispatch_base_id), ".x;");
12485 });
12486 break;
12487 case BuiltInInstanceId:
12488 case BuiltInInstanceIndex:
12489 // This is direct-mapped normally.
12490 if (!msl_options.vertex_for_tessellation)
12491 break;
12492
12493 entry_func.fixup_hooks_in.push_back([=]() {
12494 builtin_declaration = true;
12495 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12496 to_expression(builtin_invocation_id_id), ".y + ", to_expression(builtin_dispatch_base_id),
12497 ".y;");
12498 builtin_declaration = false;
12499 });
12500 break;
12501 case BuiltInBaseInstance:
12502 // This is direct-mapped normally.
12503 if (!msl_options.vertex_for_tessellation)
12504 break;
12505
12506 entry_func.fixup_hooks_in.push_back([=]() {
12507 statement(builtin_type_decl(bi_type), " ", to_expression(var_id), " = ",
12508 to_expression(builtin_dispatch_base_id), ".y;");
12509 });
12510 break;
Chip Davisf500d2f2019-01-16 17:52:53 -060012511 default:
12512 break;
12513 }
12514 }
Bill Hollingsebb50982021-07-13 21:22:13 -040012515 else if (var.storage == StorageClassOutput && get_execution_model() == ExecutionModelFragment &&
12516 is_builtin_variable(var) && active_output_builtins.get(bi_type) &&
12517 bi_type == BuiltInSampleMask && has_additional_fixed_sample_mask())
Tomek Ponitka18f23c42020-07-22 18:37:17 +020012518 {
Bill Hollingsebb50982021-07-13 21:22:13 -040012519 // If the additional fixed sample mask was set, we need to adjust the sample_mask
12520 // output to reflect that. If the shader outputs the sample_mask itself too, we need
12521 // to AND the two masks to get the final one.
12522 string op_str = does_shader_write_sample_mask ? " &= " : " = ";
12523 entry_func.fixup_hooks_out.push_back([=]() {
12524 statement(to_expression(builtin_sample_mask_id), op_str, additional_fixed_sample_mask_str(), ";");
12525 });
Tomek Ponitka18f23c42020-07-22 18:37:17 +020012526 }
Chip Davisf500d2f2019-01-16 17:52:53 -060012527 });
12528}
12529
Bill Hollings103aabf2016-04-06 17:42:27 -040012530// Returns the Metal index of the resource of the specified type as used by the specified variable.
Chip Davis39dce882019-08-02 15:11:19 -050012531uint32_t CompilerMSL::get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype, uint32_t plane)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020012532{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +020012533 auto &execution = get_entry_point();
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020012534 auto &var_dec = ir.meta[var.self].decoration;
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012535 auto &var_type = get<SPIRType>(var.basetype);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020012536 uint32_t var_desc_set = (var.storage == StorageClassPushConstant) ? kPushConstDescSet : var_dec.set;
12537 uint32_t var_binding = (var.storage == StorageClassPushConstant) ? kPushConstBinding : var_dec.binding;
Bill Hollings103aabf2016-04-06 17:42:27 -040012538
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020012539 // If a matching binding has been specified, find and use it.
12540 auto itr = resource_bindings.find({ execution.model, var_desc_set, var_binding });
Bill Hollings103aabf2016-04-06 17:42:27 -040012541
Hans-Kristian Arntzenb85ab5f2019-11-28 11:07:44 +010012542 // Atomic helper buffers for image atomics need to use secondary bindings as well.
12543 bool use_secondary_binding = (var_type.basetype == SPIRType::SampledImage && basetype == SPIRType::Sampler) ||
12544 basetype == SPIRType::AtomicCounter;
12545
Hans-Kristian Arntzenb522b402020-01-08 10:48:30 +010012546 auto resource_decoration =
12547 use_secondary_binding ? SPIRVCrossDecorationResourceIndexSecondary : SPIRVCrossDecorationResourceIndexPrimary;
Hans-Kristian Arntzenb85ab5f2019-11-28 11:07:44 +010012548
Chip Davis39dce882019-08-02 15:11:19 -050012549 if (plane == 1)
12550 resource_decoration = SPIRVCrossDecorationResourceIndexTertiary;
12551 if (plane == 2)
12552 resource_decoration = SPIRVCrossDecorationResourceIndexQuaternary;
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012553
Hans-Kristian Arntzen9bbdccd2019-02-12 11:11:29 +010012554 if (itr != end(resource_bindings))
12555 {
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020012556 auto &remap = itr->second;
12557 remap.second = true;
Hans-Kristian Arntzene74c21a2019-03-04 10:08:31 +010012558 switch (basetype)
12559 {
Hans-Kristian Arntzene74c21a2019-03-04 10:08:31 +010012560 case SPIRType::Image:
Chip Davis39dce882019-08-02 15:11:19 -050012561 set_extended_decoration(var.self, resource_decoration, remap.first.msl_texture + plane);
12562 return remap.first.msl_texture + plane;
Hans-Kristian Arntzene74c21a2019-03-04 10:08:31 +010012563 case SPIRType::Sampler:
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012564 set_extended_decoration(var.self, resource_decoration, remap.first.msl_sampler);
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020012565 return remap.first.msl_sampler;
Hans-Kristian Arntzene74c21a2019-03-04 10:08:31 +010012566 default:
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012567 set_extended_decoration(var.self, resource_decoration, remap.first.msl_buffer);
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020012568 return remap.first.msl_buffer;
Hans-Kristian Arntzene74c21a2019-03-04 10:08:31 +010012569 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020012570 }
Bill Hollings103aabf2016-04-06 17:42:27 -040012571
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012572 // If we have already allocated an index, keep using it.
12573 if (has_extended_decoration(var.self, resource_decoration))
12574 return get_extended_decoration(var.self, resource_decoration);
12575
Hans-Kristian Arntzen3136e342021-01-07 14:30:35 +010012576 auto &type = get<SPIRType>(var.basetype);
12577
12578 if (type_is_msl_framebuffer_fetch(type))
Lukas Hermanns36eab882019-09-17 11:40:01 -040012579 {
Hans-Kristian Arntzen3136e342021-01-07 14:30:35 +010012580 // Frame-buffer fetch gets its fallback resource index from the input attachment index,
12581 // which is then treated as color index.
12582 return get_decoration(var.self, DecorationInputAttachmentIndex);
12583 }
12584 else if (msl_options.enable_decoration_binding)
12585 {
12586 // Allow user to enable decoration binding.
12587 // If there is no explicit mapping of bindings to MSL, use the declared binding as a fallback.
Lukas Hermanns36eab882019-09-17 11:40:01 -040012588 if (has_decoration(var.self, DecorationBinding))
12589 {
12590 var_binding = get_decoration(var.self, DecorationBinding);
12591 // Avoid emitting sentinel bindings.
12592 if (var_binding < 0x80000000u)
12593 return var_binding;
12594 }
12595 }
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012596
12597 // If we did not explicitly remap, allocate bindings on demand.
12598 // We cannot reliably use Binding decorations since SPIR-V and MSL's binding models are very different.
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012599
Chip Davisfedbc352019-12-16 22:58:16 -060012600 bool allocate_argument_buffer_ids = false;
12601
12602 if (var.storage != StorageClassPushConstant)
12603 allocate_argument_buffer_ids = descriptor_set_is_argument_buffer(var_desc_set);
12604
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012605 uint32_t binding_stride = 1;
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012606 for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
Chip Daviscb359342019-09-05 23:14:12 -050012607 binding_stride *= to_array_size_literal(type, i);
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012608
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012609 assert(binding_stride != 0);
12610
12611 // If a binding has not been specified, revert to incrementing resource indices.
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012612 uint32_t resource_index;
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012613
Hans-Kristian Arntzen3136e342021-01-07 14:30:35 +010012614 if (allocate_argument_buffer_ids)
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012615 {
12616 // Allocate from a flat ID binding space.
Chip Davisfedbc352019-12-16 22:58:16 -060012617 resource_index = next_metal_resource_ids[var_desc_set];
12618 next_metal_resource_ids[var_desc_set] += binding_stride;
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020012619 }
12620 else
12621 {
12622 // Allocate from plain bindings which are allocated per resource type.
12623 switch (basetype)
12624 {
12625 case SPIRType::Image:
12626 resource_index = next_metal_resource_index_texture;
12627 next_metal_resource_index_texture += binding_stride;
12628 break;
12629 case SPIRType::Sampler:
12630 resource_index = next_metal_resource_index_sampler;
12631 next_metal_resource_index_sampler += binding_stride;
12632 break;
12633 default:
12634 resource_index = next_metal_resource_index_buffer;
12635 next_metal_resource_index_buffer += binding_stride;
12636 break;
12637 }
12638 }
12639
12640 set_extended_decoration(var.self, resource_decoration, resource_index);
Hans-Kristian Arntzenac81a0c2018-04-04 10:00:37 +020012641 return resource_index;
Bill Hollings103aabf2016-04-06 17:42:27 -040012642}
12643
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020012644bool CompilerMSL::type_is_msl_framebuffer_fetch(const SPIRType &type) const
12645{
Chip Davisc20d5942020-10-27 21:42:33 -050012646 return type.basetype == SPIRType::Image && type.image.dim == DimSubpassData &&
12647 msl_options.use_framebuffer_fetch_subpasses;
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020012648}
12649
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012650bool CompilerMSL::type_is_pointer(const SPIRType &type) const
12651{
12652 if (!type.pointer)
12653 return false;
12654 auto &parent_type = get<SPIRType>(type.parent_type);
12655 // Safeguards when we forget to set pointer_depth (there is an assert for it in type_to_glsl),
12656 // but the extra check shouldn't hurt.
12657 return (type.pointer_depth > parent_type.pointer_depth) || !parent_type.pointer;
12658}
12659
12660bool CompilerMSL::type_is_pointer_to_pointer(const SPIRType &type) const
12661{
12662 if (!type.pointer)
12663 return false;
12664 auto &parent_type = get<SPIRType>(type.parent_type);
12665 return type.pointer_depth > parent_type.pointer_depth && type_is_pointer(parent_type);
12666}
12667
Bill Hollings103aabf2016-04-06 17:42:27 -040012668string CompilerMSL::argument_decl(const SPIRFunction::Parameter &arg)
12669{
Bill Hollings1c180782017-11-05 21:34:42 -050012670 auto &var = get<SPIRVariable>(arg.id);
Chip Davis3bfb2f92018-12-03 02:06:33 -060012671 auto &type = get_variable_data_type(var);
12672 auto &var_type = get<SPIRType>(arg.type);
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012673 StorageClass type_storage = var_type.storage;
Chip Davis3bfb2f92018-12-03 02:06:33 -060012674 bool is_pointer = var_type.pointer;
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +020012675
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +020012676 // If we need to modify the name of the variable, make sure we use the original variable.
12677 // Our alias is just a shadow variable.
12678 uint32_t name_id = var.self;
12679 if (arg.alias_global_variable && var.basevariable)
12680 name_id = var.basevariable;
12681
Chip Davis3bfb2f92018-12-03 02:06:33 -060012682 bool constref = !arg.alias_global_variable && is_pointer && arg.write_count == 0;
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020012683 // Framebuffer fetch is plain value, const looks out of place, but it is not wrong.
12684 if (type_is_msl_framebuffer_fetch(type))
12685 constref = false;
Robert Konrada778c362017-01-15 16:39:03 +010012686
Hans-Kristian Arntzen382101b2018-04-03 14:08:15 +020012687 bool type_is_image = type.basetype == SPIRType::Image || type.basetype == SPIRType::SampledImage ||
12688 type.basetype == SPIRType::Sampler;
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020012689
12690 // Arrays of images/samplers in MSL are always const.
12691 if (!type.array.empty() && type_is_image)
12692 constref = true;
12693
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012694 const char *cv_qualifier = constref ? "const " : "";
Bill Hollings1c180782017-11-05 21:34:42 -050012695 string decl;
Bill Hollings1c180782017-11-05 21:34:42 -050012696
Chip Davis39dce882019-08-02 15:11:19 -050012697 // If this is a combined image-sampler for a 2D image with floating-point type,
12698 // we emitted the 'spvDynamicImageSampler' type, and this is *not* an alias parameter
12699 // for a global, then we need to emit a "dynamic" combined image-sampler.
12700 // Unfortunately, this is necessary to properly support passing around
12701 // combined image-samplers with Y'CbCr conversions on them.
12702 bool is_dynamic_img_sampler = !arg.alias_global_variable && type.basetype == SPIRType::SampledImage &&
12703 type.image.dim == Dim2D && type_is_floating_point(get<SPIRType>(type.image.type)) &&
12704 spv_function_implementations.count(SPVFuncImplDynamicImageSampler);
12705
Lukas Hermanns50ac6862019-09-18 14:03:54 -040012706 // Allow Metal to use the array<T> template to make arrays a value type
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012707 string address_space = get_argument_address_space(var);
Hans-Kristian Arntzen22c9b632021-04-07 12:56:09 +020012708 bool builtin = has_decoration(var.self, DecorationBuiltIn);
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012709 auto builtin_type = BuiltIn(get_decoration(arg.id, DecorationBuiltIn));
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012710
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012711 if (address_space == "threadgroup")
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010012712 is_using_builtin_array = true;
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012713
Chip Davis39dce882019-08-02 15:11:19 -050012714 if (var.basevariable && (var.basevariable == stage_in_ptr_var_id || var.basevariable == stage_out_ptr_var_id))
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012715 decl = join(cv_qualifier, type_to_glsl(type, arg.id));
Chip Daviseb89c3a2019-02-03 23:58:46 -060012716 else if (builtin)
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012717 {
12718 // Only use templated array for Clip/Cull distance when feasible.
Hans-Kristian Arntzen98619602021-04-16 15:02:26 +020012719 // In other scenarios, we need need to override array length for tess levels (if used as outputs),
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012720 // or we need to emit the expected type for builtins (uint vs int).
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012721 auto storage = get<SPIRType>(var.basetype).storage;
Hans-Kristian Arntzen98619602021-04-16 15:02:26 +020012722
12723 if (storage == StorageClassInput &&
12724 (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
12725 {
12726 is_using_builtin_array = false;
12727 }
12728 else if (builtin_type != BuiltInClipDistance && builtin_type != BuiltInCullDistance)
12729 {
12730 is_using_builtin_array = true;
12731 }
12732
Hans-Kristian Arntzen4a379a02021-04-16 14:19:07 +020012733 if (storage == StorageClassOutput && variable_storage_requires_stage_io(storage) &&
12734 !is_stage_output_builtin_masked(builtin_type))
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012735 is_using_builtin_array = true;
12736
12737 if (is_using_builtin_array)
12738 decl = join(cv_qualifier, builtin_type_decl(builtin_type, arg.id));
12739 else
12740 decl = join(cv_qualifier, type_to_glsl(type, arg.id));
12741 }
12742 else if ((type_storage == StorageClassUniform || type_storage == StorageClassStorageBuffer) && is_array(type))
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012743 {
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010012744 is_using_builtin_array = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012745 decl += join(cv_qualifier, type_to_glsl(type, arg.id), "*");
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012746 }
Chip Davis39dce882019-08-02 15:11:19 -050012747 else if (is_dynamic_img_sampler)
12748 {
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012749 decl = join(cv_qualifier, "spvDynamicImageSampler<", type_to_glsl(get<SPIRType>(type.image.type)), ">");
Chip Davis39dce882019-08-02 15:11:19 -050012750 // Mark the variable so that we can handle passing it to another function.
12751 set_extended_decoration(arg.id, SPIRVCrossDecorationDynamicImageSampler);
12752 }
Bill Hollingsa68b3272017-12-26 16:32:45 -050012753 else
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012754 {
12755 // The type is a pointer type we need to emit cv_qualifier late.
12756 if (type_is_pointer(type))
12757 {
12758 decl = type_to_glsl(type, arg.id);
12759 if (*cv_qualifier != '\0')
12760 decl += join(" ", cv_qualifier);
12761 }
12762 else
12763 decl = join(cv_qualifier, type_to_glsl(type, arg.id));
12764 }
Bill Hollings1c180782017-11-05 21:34:42 -050012765
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012766 bool opaque_handle = type_storage == StorageClassUniformConstant;
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +020012767
Chip Davis3bfb2f92018-12-03 02:06:33 -060012768 if (!builtin && !opaque_handle && !is_pointer &&
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012769 (type_storage == StorageClassFunction || type_storage == StorageClassGeneric))
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012770 {
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +020012771 // If the argument is a pure value and not an opaque type, we will pass by value.
Hans-Kristian Arntzen30343f32020-02-24 13:22:52 +010012772 if (msl_options.force_native_arrays && is_array(type))
12773 {
12774 // We are receiving an array by value. This is problematic.
12775 // We cannot be sure of the target address space since we are supposed to receive a copy,
12776 // but this is not possible with MSL without some extra work.
12777 // We will have to assume we're getting a reference in thread address space.
12778 // If we happen to get a reference in constant address space, the caller must emit a copy and pass that.
12779 // Thread const therefore becomes the only logical choice, since we cannot "create" a constant array from
12780 // non-constant arrays, but we can create thread const from constant.
12781 decl = string("thread const ") + decl;
12782 decl += " (&";
12783 const char *restrict_kw = to_restrict(name_id);
12784 if (*restrict_kw)
12785 {
12786 decl += " ";
12787 decl += restrict_kw;
12788 }
12789 decl += to_expression(name_id);
12790 decl += ")";
12791 decl += type_to_array_glsl(type);
12792 }
12793 else
12794 {
12795 if (!address_space.empty())
12796 decl = join(address_space, " ", decl);
12797 decl += " ";
12798 decl += to_expression(name_id);
12799 }
Hans-Kristian Arntzen361fe522018-08-06 15:41:10 +020012800 }
12801 else if (is_array(type) && !type_is_image)
12802 {
12803 // Arrays of images and samplers are special cased.
Chip Daviseb89c3a2019-02-03 23:58:46 -060012804 if (!address_space.empty())
12805 decl = join(address_space, " ", decl);
Hans-Kristian Arntzenaf8a9cc2019-03-15 11:29:17 +010012806
Hans-Kristian Arntzen969566a2019-03-15 11:37:34 +010012807 if (msl_options.argument_buffers)
12808 {
Hans-Kristian Arntzenfd0feb12019-05-27 16:53:30 +020012809 uint32_t desc_set = get_decoration(name_id, DecorationDescriptorSet);
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020012810 if ((type_storage == StorageClassUniform || type_storage == StorageClassStorageBuffer) &&
Hans-Kristian Arntzenfd0feb12019-05-27 16:53:30 +020012811 descriptor_set_is_argument_buffer(desc_set))
12812 {
12813 // An awkward case where we need to emit *more* address space declarations (yay!).
12814 // An example is where we pass down an array of buffer pointers to leaf functions.
12815 // It's a constant array containing pointers to constants.
12816 // The pointer array is always constant however. E.g.
12817 // device SSBO * constant (&array)[N].
12818 // const device SSBO * constant (&array)[N].
12819 // constant SSBO * constant (&array)[N].
12820 // However, this only matters for argument buffers, since for MSL 1.0 style codegen,
12821 // we emit the buffer array on stack instead, and that seems to work just fine apparently.
Hans-Kristian Arntzen4bb673a2019-10-14 12:51:48 +020012822
12823 // If the argument was marked as being in device address space, any pointer to member would
12824 // be const device, not constant.
12825 if (argument_buffer_device_storage_mask & (1u << desc_set))
12826 decl += " const device";
12827 else
12828 decl += " constant";
Hans-Kristian Arntzenfd0feb12019-05-27 16:53:30 +020012829 }
Hans-Kristian Arntzen969566a2019-03-15 11:37:34 +010012830 }
Hans-Kristian Arntzenaf8a9cc2019-03-15 11:29:17 +010012831
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012832 // Special case, need to override the array size here if we're using tess level as an argument.
12833 if (get_execution_model() == ExecutionModelTessellationControl && builtin &&
12834 (builtin_type == BuiltInTessLevelInner || builtin_type == BuiltInTessLevelOuter))
Chip Davis058f1a02019-07-10 11:17:40 -050012835 {
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +010012836 uint32_t array_size = get_physical_tess_level_array_size(builtin_type);
12837 if (array_size == 1)
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012838 {
12839 decl += " &";
12840 decl += to_expression(name_id);
12841 }
12842 else
12843 {
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012844 decl += " (&";
12845 decl += to_expression(name_id);
12846 decl += ")";
12847 decl += join("[", array_size, "]");
12848 }
Chip Davis058f1a02019-07-10 11:17:40 -050012849 }
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012850 else
12851 {
Hans-Kristian Arntzen65b5ff72021-04-06 13:27:56 +020012852 auto array_size_decl = type_to_array_glsl(type);
12853 if (array_size_decl.empty())
12854 decl += "& ";
12855 else
12856 decl += " (&";
12857
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012858 const char *restrict_kw = to_restrict(name_id);
12859 if (*restrict_kw)
12860 {
12861 decl += " ";
12862 decl += restrict_kw;
12863 }
12864 decl += to_expression(name_id);
Hans-Kristian Arntzen65b5ff72021-04-06 13:27:56 +020012865
12866 if (!array_size_decl.empty())
12867 {
12868 decl += ")";
12869 decl += array_size_decl;
12870 }
Hans-Kristian Arntzendaddbd42021-02-15 13:28:11 +010012871 }
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012872 }
Chip Davisaca9b682020-11-02 20:56:46 -060012873 else if (!opaque_handle && (!pull_model_inputs.count(var.basevariable) || type.basetype == SPIRType::Struct))
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012874 {
Chip Daviseb89c3a2019-02-03 23:58:46 -060012875 // If this is going to be a reference to a variable pointer, the address space
12876 // for the reference has to go before the '&', but after the '*'.
12877 if (!address_space.empty())
12878 {
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010012879 if (type_is_pointer(type))
12880 {
12881 if (*cv_qualifier == '\0')
12882 decl += ' ';
12883 decl += join(address_space, " ");
12884 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060012885 else
12886 decl = join(address_space, " ", decl);
12887 }
Bill Hollings1c180782017-11-05 21:34:42 -050012888 decl += "&";
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012889 decl += " ";
Chip Davis058f1a02019-07-10 11:17:40 -050012890 decl += to_restrict(name_id);
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +020012891 decl += to_expression(name_id);
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012892 }
12893 else
12894 {
Chip Daviseb89c3a2019-02-03 23:58:46 -060012895 if (!address_space.empty())
12896 decl = join(address_space, " ", decl);
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012897 decl += " ";
Hans-Kristian Arntzen87de9512018-08-27 09:59:55 +020012898 decl += to_expression(name_id);
Hans-Kristian Arntzen38b8f732018-01-29 10:57:52 +010012899 }
Bill Hollings1c180782017-11-05 21:34:42 -050012900
Lukas Hermanns50ac6862019-09-18 14:03:54 -040012901 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040012902 auto *backing_var = maybe_get_backing_variable(name_id);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020012903 if (backing_var && atomic_image_vars.count(backing_var->self))
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040012904 {
12905 decl += ", device atomic_" + type_to_glsl(get<SPIRType>(var_type.image.type), 0);
12906 decl += "* " + to_expression(name_id) + "_atomic";
12907 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040012908
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010012909 is_using_builtin_array = false;
Mark Satterthwaited50659a2019-08-13 18:18:48 -040012910
Bill Hollings1c180782017-11-05 21:34:42 -050012911 return decl;
Bill Hollings103aabf2016-04-06 17:42:27 -040012912}
12913
Bill Hollingsc45e74f2016-07-08 12:39:22 -040012914// If we're currently in the entry point function, and the object
12915// has a qualified name, use it, otherwise use the standard name.
Hans-Kristian Arntzen61c31c62017-03-07 13:27:04 +010012916string CompilerMSL::to_name(uint32_t id, bool allow_alias) const
Bill Hollingsc45e74f2016-07-08 12:39:22 -040012917{
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020012918 if (current_function && (current_function->self == ir.default_entry_point))
Bill Hollingsac00c602016-10-24 09:24:24 -040012919 {
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +010012920 auto *m = ir.find_meta(id);
12921 if (m && !m->decoration.qualified_alias.empty())
12922 return m->decoration.qualified_alias;
Bill Hollingsac00c602016-10-24 09:24:24 -040012923 }
12924 return Compiler::to_name(id, allow_alias);
Bill Hollingsc45e74f2016-07-08 12:39:22 -040012925}
12926
Bill Hollings23ff9502016-11-10 21:07:50 -050012927// Returns a name that combines the name of the struct with the name of the member, except for Builtins
Bill Hollings0943d9f2016-10-23 21:42:54 -040012928string CompilerMSL::to_qualified_member_name(const SPIRType &type, uint32_t index)
12929{
Bill Hollings23ff9502016-11-10 21:07:50 -050012930 // Don't qualify Builtin names because they are unique and are treated as such when building expressions
Hans-Kristian Arntzen53457562019-01-08 11:03:59 +010012931 BuiltIn builtin = BuiltInMax;
Bill Hollingse73e8e42016-12-17 17:07:53 -050012932 if (is_member_builtin(type, index, &builtin))
Hans-Kristian Arntzenc8d60912017-07-24 10:07:02 +020012933 return builtin_to_glsl(builtin, type.storage);
Bill Hollings23ff9502016-11-10 21:07:50 -050012934
12935 // Strip any underscore prefix from member name
Bill Hollingse73e8e42016-12-17 17:07:53 -050012936 string mbr_name = to_member_name(type, index);
Bill Hollingsac00c602016-10-24 09:24:24 -040012937 size_t startPos = mbr_name.find_first_not_of("_");
Bill Hollings5ad73f32017-03-19 21:06:21 -040012938 mbr_name = (startPos != string::npos) ? mbr_name.substr(startPos) : "";
Bill Hollingsac00c602016-10-24 09:24:24 -040012939 return join(to_name(type.self), "_", mbr_name);
Bill Hollings0943d9f2016-10-23 21:42:54 -040012940}
12941
Bill Hollingsc2e60132016-11-27 15:00:06 -050012942// Ensures that the specified name is permanently usable by prepending a prefix
12943// if the first chars are _ and a digit, which indicate a transient name.
12944string CompilerMSL::ensure_valid_name(string name, string pfx)
Bill Hollings0943d9f2016-10-23 21:42:54 -040012945{
Bill Hollings1c180782017-11-05 21:34:42 -050012946 return (name.size() >= 2 && name[0] == '_' && isdigit(name[1])) ? (pfx + name) : name;
12947}
12948
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010012949const std::unordered_set<std::string> &CompilerMSL::get_reserved_keyword_set()
Bill Hollings1c180782017-11-05 21:34:42 -050012950{
12951 static const unordered_set<string> keywords = {
Chip Davisc4b08bd2019-01-12 18:38:31 -060012952 "kernel",
12953 "vertex",
12954 "fragment",
12955 "compute",
12956 "bias",
Yuwen Wuc8a43872020-10-30 15:07:25 +080012957 "level",
12958 "gradient2d",
12959 "gradientcube",
12960 "gradient3d",
12961 "min_lod_clamp",
Chip Davisc4b08bd2019-01-12 18:38:31 -060012962 "assert",
12963 "VARIABLE_TRACEPOINT",
12964 "STATIC_DATA_TRACEPOINT",
12965 "STATIC_DATA_TRACEPOINT_V",
12966 "METAL_ALIGN",
12967 "METAL_ASM",
12968 "METAL_CONST",
12969 "METAL_DEPRECATED",
12970 "METAL_ENABLE_IF",
12971 "METAL_FUNC",
12972 "METAL_INTERNAL",
12973 "METAL_NON_NULL_RETURN",
12974 "METAL_NORETURN",
12975 "METAL_NOTHROW",
12976 "METAL_PURE",
12977 "METAL_UNAVAILABLE",
12978 "METAL_IMPLICIT",
12979 "METAL_EXPLICIT",
12980 "METAL_CONST_ARG",
12981 "METAL_ARG_UNIFORM",
12982 "METAL_ZERO_ARG",
12983 "METAL_VALID_LOD_ARG",
12984 "METAL_VALID_LEVEL_ARG",
12985 "METAL_VALID_STORE_ORDER",
12986 "METAL_VALID_LOAD_ORDER",
12987 "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
12988 "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
12989 "METAL_VALID_RENDER_TARGET",
12990 "is_function_constant_defined",
12991 "CHAR_BIT",
12992 "SCHAR_MAX",
12993 "SCHAR_MIN",
12994 "UCHAR_MAX",
12995 "CHAR_MAX",
12996 "CHAR_MIN",
12997 "USHRT_MAX",
12998 "SHRT_MAX",
12999 "SHRT_MIN",
13000 "UINT_MAX",
13001 "INT_MAX",
13002 "INT_MIN",
13003 "FLT_DIG",
13004 "FLT_MANT_DIG",
13005 "FLT_MAX_10_EXP",
13006 "FLT_MAX_EXP",
13007 "FLT_MIN_10_EXP",
13008 "FLT_MIN_EXP",
13009 "FLT_RADIX",
13010 "FLT_MAX",
13011 "FLT_MIN",
13012 "FLT_EPSILON",
13013 "FP_ILOGB0",
13014 "FP_ILOGBNAN",
13015 "MAXFLOAT",
13016 "HUGE_VALF",
13017 "INFINITY",
13018 "NAN",
13019 "M_E_F",
13020 "M_LOG2E_F",
13021 "M_LOG10E_F",
13022 "M_LN2_F",
13023 "M_LN10_F",
13024 "M_PI_F",
13025 "M_PI_2_F",
13026 "M_PI_4_F",
13027 "M_1_PI_F",
13028 "M_2_PI_F",
13029 "M_2_SQRTPI_F",
13030 "M_SQRT2_F",
13031 "M_SQRT1_2_F",
13032 "HALF_DIG",
13033 "HALF_MANT_DIG",
13034 "HALF_MAX_10_EXP",
13035 "HALF_MAX_EXP",
13036 "HALF_MIN_10_EXP",
13037 "HALF_MIN_EXP",
13038 "HALF_RADIX",
13039 "HALF_MAX",
13040 "HALF_MIN",
13041 "HALF_EPSILON",
13042 "MAXHALF",
13043 "HUGE_VALH",
13044 "M_E_H",
13045 "M_LOG2E_H",
13046 "M_LOG10E_H",
13047 "M_LN2_H",
13048 "M_LN10_H",
13049 "M_PI_H",
13050 "M_PI_2_H",
13051 "M_PI_4_H",
13052 "M_1_PI_H",
13053 "M_2_PI_H",
13054 "M_2_SQRTPI_H",
13055 "M_SQRT2_H",
13056 "M_SQRT1_2_H",
13057 "DBL_DIG",
13058 "DBL_MANT_DIG",
13059 "DBL_MAX_10_EXP",
13060 "DBL_MAX_EXP",
13061 "DBL_MIN_10_EXP",
13062 "DBL_MIN_EXP",
13063 "DBL_RADIX",
13064 "DBL_MAX",
13065 "DBL_MIN",
13066 "DBL_EPSILON",
13067 "HUGE_VAL",
13068 "M_E",
13069 "M_LOG2E",
13070 "M_LOG10E",
13071 "M_LN2",
13072 "M_LN10",
13073 "M_PI",
13074 "M_PI_2",
13075 "M_PI_4",
13076 "M_1_PI",
13077 "M_2_PI",
13078 "M_2_SQRTPI",
13079 "M_SQRT2",
13080 "M_SQRT1_2",
Chip Davis9d941572019-05-15 16:03:30 -050013081 "quad_broadcast",
Bill Hollings1c180782017-11-05 21:34:42 -050013082 };
13083
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010013084 return keywords;
13085}
13086
13087const std::unordered_set<std::string> &CompilerMSL::get_illegal_func_names()
13088{
Bill Hollings1c180782017-11-05 21:34:42 -050013089 static const unordered_set<string> illegal_func_names = {
Hans-Kristian Arntzenaa2557c2017-12-05 09:58:12 +010013090 "main",
13091 "saturate",
Chip Davisc4b08bd2019-01-12 18:38:31 -060013092 "assert",
Jan Sikorskic09a65c2020-11-27 14:55:44 +010013093 "fmin3",
13094 "fmax3",
Chip Davisc4b08bd2019-01-12 18:38:31 -060013095 "VARIABLE_TRACEPOINT",
13096 "STATIC_DATA_TRACEPOINT",
13097 "STATIC_DATA_TRACEPOINT_V",
13098 "METAL_ALIGN",
13099 "METAL_ASM",
13100 "METAL_CONST",
13101 "METAL_DEPRECATED",
13102 "METAL_ENABLE_IF",
13103 "METAL_FUNC",
13104 "METAL_INTERNAL",
13105 "METAL_NON_NULL_RETURN",
13106 "METAL_NORETURN",
13107 "METAL_NOTHROW",
13108 "METAL_PURE",
13109 "METAL_UNAVAILABLE",
13110 "METAL_IMPLICIT",
13111 "METAL_EXPLICIT",
13112 "METAL_CONST_ARG",
13113 "METAL_ARG_UNIFORM",
13114 "METAL_ZERO_ARG",
13115 "METAL_VALID_LOD_ARG",
13116 "METAL_VALID_LEVEL_ARG",
13117 "METAL_VALID_STORE_ORDER",
13118 "METAL_VALID_LOAD_ORDER",
13119 "METAL_VALID_COMPARE_EXCHANGE_FAILURE_ORDER",
13120 "METAL_COMPATIBLE_COMPARE_EXCHANGE_ORDERS",
13121 "METAL_VALID_RENDER_TARGET",
13122 "is_function_constant_defined",
13123 "CHAR_BIT",
13124 "SCHAR_MAX",
13125 "SCHAR_MIN",
13126 "UCHAR_MAX",
13127 "CHAR_MAX",
13128 "CHAR_MIN",
13129 "USHRT_MAX",
13130 "SHRT_MAX",
13131 "SHRT_MIN",
13132 "UINT_MAX",
13133 "INT_MAX",
13134 "INT_MIN",
13135 "FLT_DIG",
13136 "FLT_MANT_DIG",
13137 "FLT_MAX_10_EXP",
13138 "FLT_MAX_EXP",
13139 "FLT_MIN_10_EXP",
13140 "FLT_MIN_EXP",
13141 "FLT_RADIX",
13142 "FLT_MAX",
13143 "FLT_MIN",
13144 "FLT_EPSILON",
13145 "FP_ILOGB0",
13146 "FP_ILOGBNAN",
13147 "MAXFLOAT",
13148 "HUGE_VALF",
13149 "INFINITY",
13150 "NAN",
13151 "M_E_F",
13152 "M_LOG2E_F",
13153 "M_LOG10E_F",
13154 "M_LN2_F",
13155 "M_LN10_F",
13156 "M_PI_F",
13157 "M_PI_2_F",
13158 "M_PI_4_F",
13159 "M_1_PI_F",
13160 "M_2_PI_F",
13161 "M_2_SQRTPI_F",
13162 "M_SQRT2_F",
13163 "M_SQRT1_2_F",
13164 "HALF_DIG",
13165 "HALF_MANT_DIG",
13166 "HALF_MAX_10_EXP",
13167 "HALF_MAX_EXP",
13168 "HALF_MIN_10_EXP",
13169 "HALF_MIN_EXP",
13170 "HALF_RADIX",
13171 "HALF_MAX",
13172 "HALF_MIN",
13173 "HALF_EPSILON",
13174 "MAXHALF",
13175 "HUGE_VALH",
13176 "M_E_H",
13177 "M_LOG2E_H",
13178 "M_LOG10E_H",
13179 "M_LN2_H",
13180 "M_LN10_H",
13181 "M_PI_H",
13182 "M_PI_2_H",
13183 "M_PI_4_H",
13184 "M_1_PI_H",
13185 "M_2_PI_H",
13186 "M_2_SQRTPI_H",
13187 "M_SQRT2_H",
13188 "M_SQRT1_2_H",
13189 "DBL_DIG",
13190 "DBL_MANT_DIG",
13191 "DBL_MAX_10_EXP",
13192 "DBL_MAX_EXP",
13193 "DBL_MIN_10_EXP",
13194 "DBL_MIN_EXP",
13195 "DBL_RADIX",
13196 "DBL_MAX",
13197 "DBL_MIN",
13198 "DBL_EPSILON",
13199 "HUGE_VAL",
13200 "M_E",
13201 "M_LOG2E",
13202 "M_LOG10E",
13203 "M_LN2",
13204 "M_LN10",
13205 "M_PI",
13206 "M_PI_2",
13207 "M_PI_4",
13208 "M_1_PI",
13209 "M_2_PI",
13210 "M_2_SQRTPI",
13211 "M_SQRT2",
13212 "M_SQRT1_2",
Bill Hollings1c180782017-11-05 21:34:42 -050013213 };
13214
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010013215 return illegal_func_names;
13216}
13217
13218// Replace all names that match MSL keywords or Metal Standard Library functions.
13219void CompilerMSL::replace_illegal_names()
13220{
13221 // FIXME: MSL and GLSL are doing two different things here.
13222 // Agree on convention and remove this override.
13223 auto &keywords = get_reserved_keyword_set();
13224 auto &illegal_func_names = get_illegal_func_names();
13225
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013226 ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &) {
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +010013227 auto *meta = ir.find_meta(self);
13228 if (!meta)
13229 return;
13230
13231 auto &dec = meta->decoration;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013232 if (keywords.find(dec.alias) != end(keywords))
13233 dec.alias += "0";
13234 });
Bill Hollings1c180782017-11-05 21:34:42 -050013235
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013236 ir.for_each_typed_id<SPIRFunction>([&](uint32_t self, SPIRFunction &) {
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +010013237 auto *meta = ir.find_meta(self);
13238 if (!meta)
13239 return;
13240
13241 auto &dec = meta->decoration;
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013242 if (illegal_func_names.find(dec.alias) != end(illegal_func_names))
13243 dec.alias += "0";
13244 });
Bill Hollings1c180782017-11-05 21:34:42 -050013245
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013246 ir.for_each_typed_id<SPIRType>([&](uint32_t self, SPIRType &) {
Hans-Kristian Arntzenf79c1e22020-01-16 10:28:54 +010013247 auto *meta = ir.find_meta(self);
13248 if (!meta)
13249 return;
13250
13251 for (auto &mbr_dec : meta->members)
Hans-Kristian Arntzend92de002019-01-10 09:49:33 +010013252 if (keywords.find(mbr_dec.alias) != end(keywords))
13253 mbr_dec.alias += "0";
13254 });
Bill Hollings1c180782017-11-05 21:34:42 -050013255
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010013256 CompilerGLSL::replace_illegal_names();
13257}
13258
13259void CompilerMSL::replace_illegal_entry_point_names()
13260{
13261 auto &illegal_func_names = get_illegal_func_names();
13262
13263 // It is important to this before we fixup identifiers,
13264 // since if ep_name is reserved, we will need to fix that up,
13265 // and then copy alias back into entry.name after the fixup.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020013266 for (auto &entry : ir.entry_points)
Robert Konrada778c362017-01-15 16:39:03 +010013267 {
Bill Hollings1c180782017-11-05 21:34:42 -050013268 // Change both the entry point name and the alias, to keep them synced.
13269 string &ep_name = entry.second.name;
13270 if (illegal_func_names.find(ep_name) != end(illegal_func_names))
Bill Hollings1c180782017-11-05 21:34:42 -050013271 ep_name += "0";
Hans-Kristian Arntzen4427cb92017-11-13 13:49:11 +010013272
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020013273 ir.meta[entry.first].decoration.alias = ep_name;
Robert Konrada778c362017-01-15 16:39:03 +010013274 }
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010013275}
Hans-Kristian Arntzen3229e6e2018-04-03 15:36:35 +020013276
Hans-Kristian Arntzenc4ff1292021-01-04 09:40:11 +010013277void CompilerMSL::sync_entry_point_aliases_and_names()
13278{
13279 for (auto &entry : ir.entry_points)
13280 entry.second.name = ir.meta[entry.first].decoration.alias;
Bill Hollings0943d9f2016-10-23 21:42:54 -040013281}
13282
Chip Davis3bfb2f92018-12-03 02:06:33 -060013283string CompilerMSL::to_member_reference(uint32_t base, const SPIRType &type, uint32_t index, bool ptr_chain)
Chip Davis3a9af962018-09-26 20:06:05 -050013284{
Chip Davis3bfb2f92018-12-03 02:06:33 -060013285 auto *var = maybe_get<SPIRVariable>(base);
Chip Davis3a9af962018-09-26 20:06:05 -050013286 // If this is a buffer array, we have to dereference the buffer pointers.
Chip Davis3bfb2f92018-12-03 02:06:33 -060013287 // Otherwise, if this is a pointer expression, dereference it.
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010013288
13289 bool declared_as_pointer = false;
13290
13291 if (var)
13292 {
Hans-Kristian Arntzen3cb6aeb2020-03-31 14:09:36 +020013293 // Only allow -> dereference for block types. This is so we get expressions like
13294 // buffer[i]->first_member.second_member, rather than buffer[i]->first->second.
13295 bool is_block = has_decoration(type.self, DecorationBlock) || has_decoration(type.self, DecorationBufferBlock);
13296
13297 bool is_buffer_variable =
13298 is_block && (var->storage == StorageClassUniform || var->storage == StorageClassStorageBuffer);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010013299 declared_as_pointer = is_buffer_variable && is_array(get<SPIRType>(var->basetype));
13300 }
13301
13302 if (declared_as_pointer || (!ptr_chain && should_dereference(base)))
Chip Davis3a9af962018-09-26 20:06:05 -050013303 return join("->", to_member_name(type, index));
Chip Davisb7433c02018-09-27 11:01:46 -050013304 else
13305 return join(".", to_member_name(type, index));
Chip Davis3a9af962018-09-26 20:06:05 -050013306}
13307
Bill Hollings1c180782017-11-05 21:34:42 -050013308string CompilerMSL::to_qualifiers_glsl(uint32_t id)
13309{
13310 string quals;
13311
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013312 auto *var = maybe_get<SPIRVariable>(id);
Bill Hollings1c180782017-11-05 21:34:42 -050013313 auto &type = expression_type(id);
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013314
Hans-Kristian Arntzenae7bb412021-04-06 15:50:02 +020013315 if (type.storage == StorageClassWorkgroup || (var && variable_decl_is_remapped_storage(*var, StorageClassWorkgroup)))
Bill Hollings1c180782017-11-05 21:34:42 -050013316 quals += "threadgroup ";
13317
13318 return quals;
13319}
13320
Bill Hollingsb41e1482017-05-29 20:45:05 -040013321// The optional id parameter indicates the object whose type we are trying
13322// to find the description for. It is optional. Most type descriptions do not
13323// depend on a specific object's use of that type.
13324string CompilerMSL::type_to_glsl(const SPIRType &type, uint32_t id)
Bill Hollings103aabf2016-04-06 17:42:27 -040013325{
Bill Hollings8f6df772017-05-19 18:14:08 -040013326 string type_name;
13327
Chip Davis3bfb2f92018-12-03 02:06:33 -060013328 // Pointer?
13329 if (type.pointer)
13330 {
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010013331 assert(type.pointer_depth > 0);
13332
Chip Davis058f1a02019-07-10 11:17:40 -050013333 const char *restrict_kw;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010013334
13335 auto type_address_space = get_type_address_space(type, id);
13336 auto type_decl = type_to_glsl(get<SPIRType>(type.parent_type), id);
13337
13338 // Work around C pointer qualifier rules. If glsl_type is a pointer type as well
13339 // we'll need to emit the address space to the right.
13340 // We could always go this route, but it makes the code unnatural.
13341 // Prefer emitting thread T *foo over T thread* foo since it's more readable,
13342 // but we'll have to emit thread T * thread * T constant bar; for example.
13343 if (type_is_pointer_to_pointer(type))
13344 type_name = join(type_decl, " ", type_address_space, " ");
13345 else
13346 type_name = join(type_address_space, " ", type_decl);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013347
Chip Davis3bfb2f92018-12-03 02:06:33 -060013348 switch (type.basetype)
13349 {
13350 case SPIRType::Image:
13351 case SPIRType::SampledImage:
13352 case SPIRType::Sampler:
13353 // These are handles.
13354 break;
13355 default:
13356 // Anything else can be a raw pointer.
13357 type_name += "*";
Chip Davis058f1a02019-07-10 11:17:40 -050013358 restrict_kw = to_restrict(id);
13359 if (*restrict_kw)
13360 {
13361 type_name += " ";
13362 type_name += restrict_kw;
13363 }
Chip Davis3bfb2f92018-12-03 02:06:33 -060013364 break;
13365 }
13366 return type_name;
13367 }
13368
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013369 switch (type.basetype)
13370 {
13371 case SPIRType::Struct:
13372 // Need OpName lookup here to get a "sensible" name for a struct.
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013373 // Allow Metal to use the array<T> template to make arrays a value type
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013374 type_name = to_name(type.self);
13375 break;
Bill Hollings103aabf2016-04-06 17:42:27 -040013376
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013377 case SPIRType::Image:
13378 case SPIRType::SampledImage:
Bill Hollingsb41e1482017-05-29 20:45:05 -040013379 return image_type_glsl(type, id);
Bill Hollings103aabf2016-04-06 17:42:27 -040013380
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013381 case SPIRType::Sampler:
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013382 return sampler_type(type, id);
Bill Hollings103aabf2016-04-06 17:42:27 -040013383
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013384 case SPIRType::Void:
13385 return "void";
Bill Hollings103aabf2016-04-06 17:42:27 -040013386
Bill Hollings8f6df772017-05-19 18:14:08 -040013387 case SPIRType::AtomicCounter:
13388 return "atomic_uint";
13389
Chip Davise75add42019-02-05 18:13:26 -060013390 case SPIRType::ControlPointArray:
13391 return join("patch_control_point<", type_to_glsl(get<SPIRType>(type.parent_type), id), ">");
Hans-Kristian Arntzen6fc2a052020-11-08 13:59:52 +010013392
Chip Davisaca9b682020-11-02 20:56:46 -060013393 case SPIRType::Interpolant:
13394 return join("interpolant<", type_to_glsl(get<SPIRType>(type.parent_type), id), ", interpolation::",
13395 has_decoration(type.self, DecorationNoPerspective) ? "no_perspective" : "perspective", ">");
Chip Davise75add42019-02-05 18:13:26 -060013396
Bill Hollings8f6df772017-05-19 18:14:08 -040013397 // Scalars
13398 case SPIRType::Boolean:
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020013399 {
13400 auto *var = maybe_get_backing_variable(id);
13401 if (var && var->basevariable)
13402 var = &get<SPIRVariable>(var->basevariable);
13403
13404 // Need to special-case threadgroup booleans. They are supposed to be logical
13405 // storage, but MSL compilers will sometimes crash if you use threadgroup bool.
13406 // Workaround this by using 16-bit types instead and fixup on load-store to this data.
13407 // FIXME: We have no sane way of working around this problem if a struct member is boolean
13408 // and that struct is used as a threadgroup variable, but ... sigh.
13409 if ((var && var->storage == StorageClassWorkgroup) || type.storage == StorageClassWorkgroup)
13410 type_name = "short";
13411 else
13412 type_name = "bool";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013413 break;
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020013414 }
13415
Bill Hollings8f6df772017-05-19 18:14:08 -040013416 case SPIRType::Char:
Chip Davis117ccf42018-11-01 17:20:07 -050013417 case SPIRType::SByte:
Bill Hollings8f6df772017-05-19 18:14:08 -040013418 type_name = "char";
13419 break;
Chip Davis117ccf42018-11-01 17:20:07 -050013420 case SPIRType::UByte:
13421 type_name = "uchar";
13422 break;
13423 case SPIRType::Short:
13424 type_name = "short";
13425 break;
13426 case SPIRType::UShort:
13427 type_name = "ushort";
13428 break;
Bill Hollings8f6df772017-05-19 18:14:08 -040013429 case SPIRType::Int:
Chip Davis117ccf42018-11-01 17:20:07 -050013430 type_name = "int";
Bill Hollings8f6df772017-05-19 18:14:08 -040013431 break;
13432 case SPIRType::UInt:
Chip Davis117ccf42018-11-01 17:20:07 -050013433 type_name = "uint";
Bill Hollings8f6df772017-05-19 18:14:08 -040013434 break;
13435 case SPIRType::Int64:
Hans-Kristian Arntzena6b71ae2019-06-11 10:45:22 +020013436 if (!msl_options.supports_msl_version(2, 2))
13437 SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
13438 type_name = "long";
Bill Hollings8f6df772017-05-19 18:14:08 -040013439 break;
13440 case SPIRType::UInt64:
Hans-Kristian Arntzena6b71ae2019-06-11 10:45:22 +020013441 if (!msl_options.supports_msl_version(2, 2))
13442 SPIRV_CROSS_THROW("64-bit integers are only supported in MSL 2.2 and above.");
13443 type_name = "ulong";
Bill Hollings8f6df772017-05-19 18:14:08 -040013444 break;
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +010013445 case SPIRType::Half:
13446 type_name = "half";
13447 break;
Bill Hollings8f6df772017-05-19 18:14:08 -040013448 case SPIRType::Float:
Hans-Kristian Arntzend9da2db2018-03-06 17:07:59 +010013449 type_name = "float";
Bill Hollings8f6df772017-05-19 18:14:08 -040013450 break;
13451 case SPIRType::Double:
13452 type_name = "double"; // Currently unsupported
13453 break;
丛越597f29d2021-10-19 18:45:10 +080013454 case SPIRType::AccelerationStructure:
丛越d52ec1e2021-10-21 17:46:45 +080013455 if (msl_options.supports_msl_version(2, 4))
13456 type_name = "acceleration_structure<instancing>";
13457 else if (msl_options.supports_msl_version(2, 3))
13458 type_name = "instance_acceleration_structure";
13459 else
13460 SPIRV_CROSS_THROW("Acceleration Structure Type is supported in MSL 2.3 and above.");
丛越597f29d2021-10-19 18:45:10 +080013461 break;
13462 case SPIRType::RayQuery:
Hans-Kristian Arntzen2b5e17e2021-10-21 22:02:01 +020013463 return "intersection_query<instancing, triangle_data>";
Bill Hollings8f6df772017-05-19 18:14:08 -040013464
13465 default:
13466 return "unknown_type";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013467 }
Bill Hollings103aabf2016-04-06 17:42:27 -040013468
Bill Hollings8f6df772017-05-19 18:14:08 -040013469 // Matrix?
13470 if (type.columns > 1)
13471 type_name += to_string(type.columns) + "x";
13472
13473 // Vector or Matrix?
13474 if (type.vecsize > 1)
13475 type_name += to_string(type.vecsize);
13476
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010013477 if (type.array.empty() || using_builtin_array())
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013478 {
13479 return type_name;
13480 }
13481 else
13482 {
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020013483 // Allow Metal to use the array<T> template to make arrays a value type
13484 add_spv_func_and_recompile(SPVFuncImplUnsafeArray);
13485 string res;
13486 string sizes;
13487
Hans-Kristian Arntzen1fc33472019-10-26 15:40:56 +020013488 for (uint32_t i = 0; i < uint32_t(type.array.size()); i++)
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013489 {
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020013490 res += "spvUnsafeArray<";
13491 sizes += ", ";
Hans-Kristian Arntzen1fc33472019-10-26 15:40:56 +020013492 sizes += to_array_size(type, i);
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020013493 sizes += ">";
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013494 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013495
Hans-Kristian Arntzen27672572019-10-24 13:57:05 +020013496 res += type_name + sizes;
13497 return res;
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013498 }
Bill Hollings103aabf2016-04-06 17:42:27 -040013499}
13500
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013501string CompilerMSL::type_to_array_glsl(const SPIRType &type)
13502{
Lukas Hermanns50ac6862019-09-18 14:03:54 -040013503 // Allow Metal to use the array<T> template to make arrays a value type
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013504 switch (type.basetype)
13505 {
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013506 case SPIRType::AtomicCounter:
13507 case SPIRType::ControlPointArray:
Hans-Kristian Arntzen2b5e17e2021-10-21 22:02:01 +020013508 case SPIRType::RayQuery:
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013509 {
13510 return CompilerGLSL::type_to_array_glsl(type);
13511 }
13512 default:
13513 {
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010013514 if (using_builtin_array())
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013515 return CompilerGLSL::type_to_array_glsl(type);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040013516 else
13517 return "";
13518 }
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013519 }
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013520}
13521
Bill Hollings5fb1ca42021-09-03 18:20:49 -040013522string CompilerMSL::constant_op_expression(const SPIRConstantOp &cop)
13523{
Bill Hollings5fb1ca42021-09-03 18:20:49 -040013524 switch (cop.opcode)
13525 {
13526 case OpQuantizeToF16:
Bill Hollingsec054da2021-09-28 19:10:16 -040013527 add_spv_func_and_recompile(SPVFuncImplQuantizeToF16);
13528 return join("spvQuantizeToF16(", to_expression(cop.arguments[0]), ")");
Bill Hollings5fb1ca42021-09-03 18:20:49 -040013529 default:
13530 return CompilerGLSL::constant_op_expression(cop);
13531 }
13532}
13533
Hans-Kristian Arntzenae7bb412021-04-06 15:50:02 +020013534bool CompilerMSL::variable_decl_is_remapped_storage(const SPIRVariable &variable, spv::StorageClass storage) const
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013535{
Hans-Kristian Arntzenae7bb412021-04-06 15:50:02 +020013536 if (variable.storage == storage)
13537 return true;
13538
13539 if (storage == StorageClassWorkgroup)
13540 {
13541 auto model = get_execution_model();
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +020013542
13543 // Specially masked IO block variable.
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +020013544 // Normally, we will never access IO blocks directly here.
13545 // The only scenario which that should occur is with a masked IO block.
13546 if (model == ExecutionModelTessellationControl && variable.storage == StorageClassOutput &&
13547 has_decoration(get<SPIRType>(variable.basetype).self, DecorationBlock))
13548 {
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +020013549 return true;
Hans-Kristian Arntzene32c4742021-04-09 13:23:09 +020013550 }
Hans-Kristian Arntzen6ecdd642021-04-07 13:36:22 +020013551
Hans-Kristian Arntzenae7bb412021-04-06 15:50:02 +020013552 return variable.storage == StorageClassOutput &&
13553 model == ExecutionModelTessellationControl &&
13554 is_stage_output_variable_masked(variable);
13555 }
13556 else if (storage == StorageClassStorageBuffer)
13557 {
13558 // We won't be able to catch writes to control point outputs here since variable
13559 // refers to a function local pointer.
13560 // This is fine, as there cannot be concurrent writers to that memory anyways,
13561 // so we just ignore that case.
13562
Hans-Kristian Arntzenae9ca7d2021-04-19 11:46:30 +020013563 return (variable.storage == StorageClassOutput || variable.storage == StorageClassInput) &&
13564 !variable_storage_requires_stage_io(variable.storage) &&
13565 (variable.storage != StorageClassOutput || !is_stage_output_variable_masked(variable));
Hans-Kristian Arntzenae7bb412021-04-06 15:50:02 +020013566 }
13567 else
13568 {
13569 return false;
13570 }
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013571}
13572
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013573std::string CompilerMSL::variable_decl(const SPIRVariable &variable)
13574{
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013575 bool old_is_using_builtin_array = is_using_builtin_array;
Hans-Kristian Arntzen50a6bc02021-04-06 12:25:22 +020013576
13577 // Threadgroup arrays can't have a wrapper type.
Hans-Kristian Arntzenc1edd352021-04-16 11:45:50 +020013578 if (variable_decl_is_remapped_storage(variable, StorageClassWorkgroup))
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010013579 is_using_builtin_array = true;
Hans-Kristian Arntzen50a6bc02021-04-06 12:25:22 +020013580
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013581 std::string expr = CompilerGLSL::variable_decl(variable);
Hans-Kristian Arntzenf2b5fb32021-03-26 17:23:44 +010013582 is_using_builtin_array = old_is_using_builtin_array;
Mark Satterthwaited50659a2019-08-13 18:18:48 -040013583 return expr;
Bill Hollings103aabf2016-04-06 17:42:27 -040013584}
13585
Lukas Hermannsf3a6d282019-09-27 15:49:54 -040013586// GCC workaround of lambdas calling protected funcs
13587std::string CompilerMSL::variable_decl(const SPIRType &type, const std::string &name, uint32_t id)
13588{
13589 return CompilerGLSL::variable_decl(type, name, id);
Bill Hollings103aabf2016-04-06 17:42:27 -040013590}
13591
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013592std::string CompilerMSL::sampler_type(const SPIRType &type, uint32_t id)
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013593{
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013594 auto *var = maybe_get<SPIRVariable>(id);
13595 if (var && var->basevariable)
13596 {
13597 // Check against the base variable, and not a fake ID which might have been generated for this variable.
13598 id = var->basevariable;
13599 }
13600
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013601 if (!type.array.empty())
13602 {
Hans-Kristian Arntzene8ca39b2018-04-03 14:26:24 +020013603 if (!msl_options.supports_msl_version(2))
13604 SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of samplers.");
13605
Chip Davisb7433c02018-09-27 11:01:46 -050013606 if (type.array.size() > 1)
13607 SPIRV_CROSS_THROW("Arrays of arrays of samplers are not supported in MSL.");
13608
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013609 // Arrays of samplers in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013610 // If we have a runtime array, it could be a variable-count descriptor set binding.
Hans-Kristian Arntzen480acda2018-11-01 14:56:25 +010013611 uint32_t array_size = to_array_size_literal(type);
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013612 if (array_size == 0)
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013613 array_size = get_resource_array_size(id);
13614
13615 if (array_size == 0)
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013616 SPIRV_CROSS_THROW("Unsized array of samplers is not supported in MSL.");
Bill Hollingse0910312018-06-24 15:06:12 -040013617
Chip Davisfc02b3d2019-01-08 12:54:40 -060013618 auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013619 return join("array<", sampler_type(parent, id), ", ", array_size, ">");
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013620 }
13621 else
13622 return "sampler";
13623}
13624
Bill Hollingsac238b82018-07-26 00:50:33 -040013625// Returns an MSL string describing the SPIR-V image type
Bill Hollingsb41e1482017-05-29 20:45:05 -040013626string CompilerMSL::image_type_glsl(const SPIRType &type, uint32_t id)
Bill Hollings103aabf2016-04-06 17:42:27 -040013627{
Hans-Kristian Arntzen8175e2e2018-04-10 12:31:13 +020013628 auto *var = maybe_get<SPIRVariable>(id);
13629 if (var && var->basevariable)
13630 {
13631 // For comparison images, check against the base variable,
13632 // and not the fake ID which might have been generated for this variable.
13633 id = var->basevariable;
13634 }
13635
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013636 if (!type.array.empty())
13637 {
Chip Davis3a9af962018-09-26 20:06:05 -050013638 uint32_t major = 2, minor = 0;
13639 if (msl_options.is_ios())
13640 {
13641 major = 1;
13642 minor = 2;
13643 }
13644 if (!msl_options.supports_msl_version(major, minor))
Chip Davisb7433c02018-09-27 11:01:46 -050013645 {
13646 if (msl_options.is_ios())
13647 SPIRV_CROSS_THROW("MSL 1.2 or greater is required for arrays of textures.");
13648 else
13649 SPIRV_CROSS_THROW("MSL 2.0 or greater is required for arrays of textures.");
13650 }
13651
13652 if (type.array.size() > 1)
13653 SPIRV_CROSS_THROW("Arrays of arrays of textures are not supported in MSL.");
Hans-Kristian Arntzene8ca39b2018-04-03 14:26:24 +020013654
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013655 // Arrays of images in MSL must be declared with a special array<T, N> syntax ala C++11 std::array.
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013656 // If we have a runtime array, it could be a variable-count descriptor set binding.
Hans-Kristian Arntzen480acda2018-11-01 14:56:25 +010013657 uint32_t array_size = to_array_size_literal(type);
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013658 if (array_size == 0)
Bill Hollingsb7b0e802020-10-29 18:50:42 -040013659 array_size = get_resource_array_size(id);
13660
13661 if (array_size == 0)
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013662 SPIRV_CROSS_THROW("Unsized array of images is not supported in MSL.");
Bill Hollingse0910312018-06-24 15:06:12 -040013663
Chip Davisfc02b3d2019-01-08 12:54:40 -060013664 auto &parent = get<SPIRType>(get_pointee_type(type).parent_type);
Bill Hollingse0910312018-06-24 15:06:12 -040013665 return join("array<", image_type_glsl(parent, id), ", ", array_size, ">");
Hans-Kristian Arntzen5827dd52018-04-03 14:00:34 +020013666 }
13667
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013668 string img_type_name;
Bill Hollings1dbd18d2016-04-21 20:47:57 -040013669
Bill Hollings8f6df772017-05-19 18:14:08 -040013670 // Bypass pointers because we need the real image struct
13671 auto &img_type = get<SPIRType>(type.self).image;
Bill Hollingsfd252b22021-11-08 15:59:45 -050013672 if (is_depth_image(type, id))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013673 {
13674 switch (img_type.dim)
13675 {
Bill Hollings77f58122017-08-11 14:54:58 -040013676 case Dim1D:
Hans-Kristian Arntzen40cc0a02019-10-28 15:20:38 +010013677 case Dim2D:
13678 if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
Bill Hollings4b5c6c12019-10-24 12:31:20 -040013679 {
13680 // Use a native Metal 1D texture
13681 img_type_name += "depth1d_unsupported_by_metal";
13682 break;
13683 }
Hans-Kristian Arntzen40cc0a02019-10-28 15:20:38 +010013684
Hans-Kristian Arntzen778f9982018-09-03 10:21:59 +020013685 if (img_type.ms && img_type.arrayed)
Hans-Kristian Arntzen0c1d4d82018-09-03 11:02:31 +020013686 {
13687 if (!msl_options.supports_msl_version(2, 1))
13688 SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
13689 img_type_name += "depth2d_ms_array";
13690 }
13691 else if (img_type.ms)
13692 img_type_name += "depth2d_ms";
13693 else if (img_type.arrayed)
13694 img_type_name += "depth2d_array";
13695 else
13696 img_type_name += "depth2d";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013697 break;
Bill Hollings77f58122017-08-11 14:54:58 -040013698 case Dim3D:
13699 img_type_name += "depth3d_unsupported_by_metal";
13700 break;
Bill Hollingsb41e1482017-05-29 20:45:05 -040013701 case DimCube:
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -040013702 if (!msl_options.emulate_cube_array)
13703 img_type_name += (img_type.arrayed ? "depthcube_array" : "depthcube");
13704 else
13705 img_type_name += (img_type.arrayed ? "depth2d_array" : "depthcube");
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013706 break;
13707 default:
13708 img_type_name += "unknown_depth_texture_type";
13709 break;
13710 }
13711 }
13712 else
13713 {
13714 switch (img_type.dim)
13715 {
Bill Hollingsb41e1482017-05-29 20:45:05 -040013716 case DimBuffer:
Hans-Kristian Arntzenfc4f39b2019-04-23 12:17:21 +020013717 if (img_type.ms || img_type.arrayed)
13718 SPIRV_CROSS_THROW("Cannot use texel buffers with multisampling or array layers.");
13719
13720 if (msl_options.texture_buffer_native)
13721 {
13722 if (!msl_options.supports_msl_version(2, 1))
13723 SPIRV_CROSS_THROW("Native texture_buffer type is only supported in MSL 2.1.");
13724 img_type_name = "texture_buffer";
13725 }
13726 else
13727 img_type_name += "texture2d";
13728 break;
Bill Hollings4b5c6c12019-10-24 12:31:20 -040013729 case Dim1D:
Hans-Kristian Arntzen40cc0a02019-10-28 15:20:38 +010013730 case Dim2D:
13731 case DimSubpassData:
Chip Davis4cf840e2020-08-27 19:24:20 -050013732 {
13733 bool subpass_array =
13734 img_type.dim == DimSubpassData && (msl_options.multiview || msl_options.arrayed_subpass_input);
Hans-Kristian Arntzen40cc0a02019-10-28 15:20:38 +010013735 if (img_type.dim == Dim1D && !msl_options.texture_1D_as_2D)
Bill Hollings4b5c6c12019-10-24 12:31:20 -040013736 {
13737 // Use a native Metal 1D texture
13738 img_type_name += (img_type.arrayed ? "texture1d_array" : "texture1d");
13739 break;
13740 }
Hans-Kristian Arntzen40cc0a02019-10-28 15:20:38 +010013741
Lukas Hermanns50ac6862019-09-18 14:03:54 -040013742 // Use Metal's native frame-buffer fetch API for subpass inputs.
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020013743 if (type_is_msl_framebuffer_fetch(type))
Lukas Hermannsf3a6d282019-09-27 15:49:54 -040013744 {
Hans-Kristian Arntzen6ef47d62020-04-27 11:23:24 +020013745 auto img_type_4 = get<SPIRType>(img_type.type);
13746 img_type_4.vecsize = 4;
13747 return type_to_glsl(img_type_4);
Lukas Hermannsf3a6d282019-09-27 15:49:54 -040013748 }
Chip Davis4cf840e2020-08-27 19:24:20 -050013749 if (img_type.ms && (img_type.arrayed || subpass_array))
Hans-Kristian Arntzen0c1d4d82018-09-03 11:02:31 +020013750 {
13751 if (!msl_options.supports_msl_version(2, 1))
13752 SPIRV_CROSS_THROW("Multisampled array textures are supported from 2.1.");
13753 img_type_name += "texture2d_ms_array";
13754 }
13755 else if (img_type.ms)
13756 img_type_name += "texture2d_ms";
Chip Davis4cf840e2020-08-27 19:24:20 -050013757 else if (img_type.arrayed || subpass_array)
Hans-Kristian Arntzen0c1d4d82018-09-03 11:02:31 +020013758 img_type_name += "texture2d_array";
13759 else
13760 img_type_name += "texture2d";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013761 break;
Chip Davis4cf840e2020-08-27 19:24:20 -050013762 }
Bill Hollingsb41e1482017-05-29 20:45:05 -040013763 case Dim3D:
Bill Hollingsc2e60132016-11-27 15:00:06 -050013764 img_type_name += "texture3d";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013765 break;
Bill Hollingsb41e1482017-05-29 20:45:05 -040013766 case DimCube:
Lukas Hermanns7cf5d4f2019-09-13 17:24:27 -040013767 if (!msl_options.emulate_cube_array)
13768 img_type_name += (img_type.arrayed ? "texturecube_array" : "texturecube");
13769 else
13770 img_type_name += (img_type.arrayed ? "texture2d_array" : "texturecube");
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013771 break;
13772 default:
13773 img_type_name += "unknown_texture_type";
13774 break;
13775 }
13776 }
Bill Hollings103aabf2016-04-06 17:42:27 -040013777
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013778 // Append the pixel type
Bill Hollings8f6df772017-05-19 18:14:08 -040013779 img_type_name += "<";
Bill Hollingsb41e1482017-05-29 20:45:05 -040013780 img_type_name += type_to_glsl(get<SPIRType>(img_type.type));
Bill Hollings8f6df772017-05-19 18:14:08 -040013781
Bill Hollingsb41e1482017-05-29 20:45:05 -040013782 // For unsampled images, append the sample/read/write access qualifier.
13783 // For kernel images, the access qualifier my be supplied directly by SPIR-V.
13784 // Otherwise it may be set based on whether the image is read from or written to within the shader.
Hans-Kristian Arntzen09124272018-02-09 11:27:23 +010013785 if (type.basetype == SPIRType::Image && type.image.sampled == 2 && type.image.dim != DimSubpassData)
Bill Hollings8f6df772017-05-19 18:14:08 -040013786 {
Bill Hollingsb41e1482017-05-29 20:45:05 -040013787 switch (img_type.access)
13788 {
13789 case AccessQualifierReadOnly:
13790 img_type_name += ", access::read";
13791 break;
Bill Hollings8f6df772017-05-19 18:14:08 -040013792
Bill Hollingsb41e1482017-05-29 20:45:05 -040013793 case AccessQualifierWriteOnly:
13794 img_type_name += ", access::write";
13795 break;
Bill Hollings8f6df772017-05-19 18:14:08 -040013796
Bill Hollingsb41e1482017-05-29 20:45:05 -040013797 case AccessQualifierReadWrite:
13798 img_type_name += ", access::read_write";
13799 break;
13800
13801 default:
13802 {
13803 auto *p_var = maybe_get_backing_variable(id);
Vadim Shcherbakov6c41f9e2017-12-06 09:51:23 -080013804 if (p_var && p_var->basevariable)
13805 p_var = maybe_get<SPIRVariable>(p_var->basevariable);
Bill Hollingsb41e1482017-05-29 20:45:05 -040013806 if (p_var && !has_decoration(p_var->self, DecorationNonWritable))
13807 {
13808 img_type_name += ", access::";
13809
13810 if (!has_decoration(p_var->self, DecorationNonReadable))
13811 img_type_name += "read_";
13812
13813 img_type_name += "write";
13814 }
13815 break;
13816 }
13817 }
Bill Hollings8f6df772017-05-19 18:14:08 -040013818 }
13819
13820 img_type_name += ">";
Bill Hollings1dbd18d2016-04-21 20:47:57 -040013821
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020013822 return img_type_name;
Bill Hollings103aabf2016-04-06 17:42:27 -040013823}
13824
Chip Davis9d941572019-05-15 16:03:30 -050013825void CompilerMSL::emit_subgroup_op(const Instruction &i)
13826{
13827 const uint32_t *ops = stream(i);
13828 auto op = static_cast<Op>(i.op);
13829
Chip Davis68908352020-11-18 23:16:46 -060013830 if (msl_options.emulate_subgroups)
13831 {
13832 // In this mode, only the GroupNonUniform cap is supported. The only op
13833 // we need to handle, then, is OpGroupNonUniformElect.
13834 if (op != OpGroupNonUniformElect)
13835 SPIRV_CROSS_THROW("Subgroup emulation does not support operations other than Elect.");
13836 // In this mode, the subgroup size is assumed to be one, so every invocation
13837 // is elected.
13838 emit_op(ops[0], ops[1], "true", true);
13839 return;
13840 }
13841
13842 // Metal 2.0 is required. iOS only supports quad ops on 11.0 (2.0), with
13843 // full support in 13.0 (2.2). macOS only supports broadcast and shuffle on
13844 // 10.13 (2.0), with full support in 10.14 (2.1).
13845 // Note that Apple GPUs before A13 make no distinction between a quad-group
13846 // and a SIMD-group; all SIMD-groups are quad-groups on those.
Chip Davis9d941572019-05-15 16:03:30 -050013847 if (!msl_options.supports_msl_version(2))
13848 SPIRV_CROSS_THROW("Subgroups are only supported in Metal 2.0 and up.");
13849
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010013850 // If we need to do implicit bitcasts, make sure we do it with the correct type.
13851 uint32_t integer_width = get_integer_width_for_instruction(i);
13852 auto int_type = to_signed_basetype(integer_width);
13853 auto uint_type = to_unsigned_basetype(integer_width);
13854
Chip Davis68908352020-11-18 23:16:46 -060013855 if (msl_options.is_ios() && (!msl_options.supports_msl_version(2, 3) || !msl_options.ios_use_simdgroup_functions))
Chip Davis9d941572019-05-15 16:03:30 -050013856 {
13857 switch (op)
13858 {
13859 default:
Chip Davis68908352020-11-18 23:16:46 -060013860 SPIRV_CROSS_THROW("Subgroup ops beyond broadcast, ballot, and shuffle on iOS require Metal 2.3 and up.");
13861 case OpGroupNonUniformBroadcastFirst:
13862 if (!msl_options.supports_msl_version(2, 2))
13863 SPIRV_CROSS_THROW("BroadcastFirst on iOS requires Metal 2.2 and up.");
13864 break;
13865 case OpGroupNonUniformElect:
13866 if (!msl_options.supports_msl_version(2, 2))
13867 SPIRV_CROSS_THROW("Elect on iOS requires Metal 2.2 and up.");
13868 break;
13869 case OpGroupNonUniformAny:
13870 case OpGroupNonUniformAll:
13871 case OpGroupNonUniformAllEqual:
13872 case OpGroupNonUniformBallot:
13873 case OpGroupNonUniformInverseBallot:
13874 case OpGroupNonUniformBallotBitExtract:
13875 case OpGroupNonUniformBallotFindLSB:
13876 case OpGroupNonUniformBallotFindMSB:
13877 case OpGroupNonUniformBallotBitCount:
13878 if (!msl_options.supports_msl_version(2, 2))
13879 SPIRV_CROSS_THROW("Ballot ops on iOS requires Metal 2.2 and up.");
13880 break;
Chip Davis9d941572019-05-15 16:03:30 -050013881 case OpGroupNonUniformBroadcast:
13882 case OpGroupNonUniformShuffle:
13883 case OpGroupNonUniformShuffleXor:
13884 case OpGroupNonUniformShuffleUp:
13885 case OpGroupNonUniformShuffleDown:
13886 case OpGroupNonUniformQuadSwap:
13887 case OpGroupNonUniformQuadBroadcast:
13888 break;
13889 }
13890 }
13891
13892 if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 1))
13893 {
13894 switch (op)
13895 {
13896 default:
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010013897 SPIRV_CROSS_THROW("Subgroup ops beyond broadcast and shuffle on macOS require Metal 2.1 and up.");
Chip Davis9d941572019-05-15 16:03:30 -050013898 case OpGroupNonUniformBroadcast:
13899 case OpGroupNonUniformShuffle:
13900 case OpGroupNonUniformShuffleXor:
13901 case OpGroupNonUniformShuffleUp:
13902 case OpGroupNonUniformShuffleDown:
13903 break;
13904 }
13905 }
13906
13907 uint32_t result_type = ops[0];
13908 uint32_t id = ops[1];
13909
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +020013910 auto scope = static_cast<Scope>(evaluate_constant_u32(ops[2]));
Chip Davis9d941572019-05-15 16:03:30 -050013911 if (scope != ScopeSubgroup)
13912 SPIRV_CROSS_THROW("Only subgroup scope is supported.");
13913
13914 switch (op)
13915 {
13916 case OpGroupNonUniformElect:
Chip Davis68908352020-11-18 23:16:46 -060013917 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
13918 emit_op(result_type, id, "quad_is_first()", false);
13919 else
13920 emit_op(result_type, id, "simd_is_first()", false);
Chip Davis9d941572019-05-15 16:03:30 -050013921 break;
13922
13923 case OpGroupNonUniformBroadcast:
Chip Davis1264e272020-10-21 01:51:48 -050013924 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupBroadcast");
Chip Davis9d941572019-05-15 16:03:30 -050013925 break;
13926
13927 case OpGroupNonUniformBroadcastFirst:
Chip Davis1264e272020-10-21 01:51:48 -050013928 emit_unary_func_op(result_type, id, ops[3], "spvSubgroupBroadcastFirst");
Chip Davis9d941572019-05-15 16:03:30 -050013929 break;
13930
13931 case OpGroupNonUniformBallot:
13932 emit_unary_func_op(result_type, id, ops[3], "spvSubgroupBallot");
13933 break;
13934
13935 case OpGroupNonUniformInverseBallot:
13936 emit_binary_func_op(result_type, id, ops[3], builtin_subgroup_invocation_id_id, "spvSubgroupBallotBitExtract");
13937 break;
13938
13939 case OpGroupNonUniformBallotBitExtract:
13940 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupBallotBitExtract");
13941 break;
13942
13943 case OpGroupNonUniformBallotFindLSB:
Chip Davis065b5bd2020-10-20 23:59:30 -050013944 emit_binary_func_op(result_type, id, ops[3], builtin_subgroup_size_id, "spvSubgroupBallotFindLSB");
Chip Davis9d941572019-05-15 16:03:30 -050013945 break;
13946
13947 case OpGroupNonUniformBallotFindMSB:
Chip Davis065b5bd2020-10-20 23:59:30 -050013948 emit_binary_func_op(result_type, id, ops[3], builtin_subgroup_size_id, "spvSubgroupBallotFindMSB");
Chip Davis9d941572019-05-15 16:03:30 -050013949 break;
13950
13951 case OpGroupNonUniformBallotBitCount:
13952 {
13953 auto operation = static_cast<GroupOperation>(ops[3]);
Chip Davis065b5bd2020-10-20 23:59:30 -050013954 switch (operation)
13955 {
13956 case GroupOperationReduce:
13957 emit_binary_func_op(result_type, id, ops[4], builtin_subgroup_size_id, "spvSubgroupBallotBitCount");
13958 break;
13959 case GroupOperationInclusiveScan:
Chip Davis9d941572019-05-15 16:03:30 -050013960 emit_binary_func_op(result_type, id, ops[4], builtin_subgroup_invocation_id_id,
13961 "spvSubgroupBallotInclusiveBitCount");
Chip Davis065b5bd2020-10-20 23:59:30 -050013962 break;
13963 case GroupOperationExclusiveScan:
Chip Davis9d941572019-05-15 16:03:30 -050013964 emit_binary_func_op(result_type, id, ops[4], builtin_subgroup_invocation_id_id,
13965 "spvSubgroupBallotExclusiveBitCount");
Chip Davis065b5bd2020-10-20 23:59:30 -050013966 break;
13967 default:
Chip Davis9d941572019-05-15 16:03:30 -050013968 SPIRV_CROSS_THROW("Invalid BitCount operation.");
Chip Davis065b5bd2020-10-20 23:59:30 -050013969 }
Chip Davis9d941572019-05-15 16:03:30 -050013970 break;
13971 }
13972
13973 case OpGroupNonUniformShuffle:
Chip Davis1264e272020-10-21 01:51:48 -050013974 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupShuffle");
Chip Davis9d941572019-05-15 16:03:30 -050013975 break;
13976
13977 case OpGroupNonUniformShuffleXor:
Chip Davis1264e272020-10-21 01:51:48 -050013978 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupShuffleXor");
Chip Davis9d941572019-05-15 16:03:30 -050013979 break;
13980
13981 case OpGroupNonUniformShuffleUp:
Chip Davis1264e272020-10-21 01:51:48 -050013982 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupShuffleUp");
Chip Davis9d941572019-05-15 16:03:30 -050013983 break;
13984
13985 case OpGroupNonUniformShuffleDown:
Chip Davis1264e272020-10-21 01:51:48 -050013986 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvSubgroupShuffleDown");
Chip Davis9d941572019-05-15 16:03:30 -050013987 break;
13988
13989 case OpGroupNonUniformAll:
Chip Davis68908352020-11-18 23:16:46 -060013990 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
13991 emit_unary_func_op(result_type, id, ops[3], "quad_all");
13992 else
13993 emit_unary_func_op(result_type, id, ops[3], "simd_all");
Chip Davis9d941572019-05-15 16:03:30 -050013994 break;
13995
13996 case OpGroupNonUniformAny:
Chip Davis68908352020-11-18 23:16:46 -060013997 if (msl_options.is_ios() && !msl_options.ios_use_simdgroup_functions)
13998 emit_unary_func_op(result_type, id, ops[3], "quad_any");
13999 else
14000 emit_unary_func_op(result_type, id, ops[3], "simd_any");
Chip Davis9d941572019-05-15 16:03:30 -050014001 break;
14002
14003 case OpGroupNonUniformAllEqual:
14004 emit_unary_func_op(result_type, id, ops[3], "spvSubgroupAllEqual");
14005 break;
14006
14007 // clang-format off
14008#define MSL_GROUP_OP(op, msl_op) \
14009case OpGroupNonUniform##op: \
14010 { \
14011 auto operation = static_cast<GroupOperation>(ops[3]); \
14012 if (operation == GroupOperationReduce) \
14013 emit_unary_func_op(result_type, id, ops[4], "simd_" #msl_op); \
14014 else if (operation == GroupOperationInclusiveScan) \
14015 emit_unary_func_op(result_type, id, ops[4], "simd_prefix_inclusive_" #msl_op); \
14016 else if (operation == GroupOperationExclusiveScan) \
14017 emit_unary_func_op(result_type, id, ops[4], "simd_prefix_exclusive_" #msl_op); \
14018 else if (operation == GroupOperationClusteredReduce) \
14019 { \
14020 /* Only cluster sizes of 4 are supported. */ \
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +020014021 uint32_t cluster_size = evaluate_constant_u32(ops[5]); \
Chip Davis9d941572019-05-15 16:03:30 -050014022 if (cluster_size != 4) \
14023 SPIRV_CROSS_THROW("Metal only supports quad ClusteredReduce."); \
14024 emit_unary_func_op(result_type, id, ops[4], "quad_" #msl_op); \
14025 } \
14026 else \
14027 SPIRV_CROSS_THROW("Invalid group operation."); \
14028 break; \
14029 }
14030 MSL_GROUP_OP(FAdd, sum)
14031 MSL_GROUP_OP(FMul, product)
14032 MSL_GROUP_OP(IAdd, sum)
14033 MSL_GROUP_OP(IMul, product)
14034#undef MSL_GROUP_OP
14035 // The others, unfortunately, don't support InclusiveScan or ExclusiveScan.
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010014036
Chip Davis9d941572019-05-15 16:03:30 -050014037#define MSL_GROUP_OP(op, msl_op) \
14038case OpGroupNonUniform##op: \
14039 { \
14040 auto operation = static_cast<GroupOperation>(ops[3]); \
14041 if (operation == GroupOperationReduce) \
14042 emit_unary_func_op(result_type, id, ops[4], "simd_" #msl_op); \
14043 else if (operation == GroupOperationInclusiveScan) \
14044 SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
14045 else if (operation == GroupOperationExclusiveScan) \
14046 SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
14047 else if (operation == GroupOperationClusteredReduce) \
14048 { \
14049 /* Only cluster sizes of 4 are supported. */ \
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +020014050 uint32_t cluster_size = evaluate_constant_u32(ops[5]); \
Chip Davis9d941572019-05-15 16:03:30 -050014051 if (cluster_size != 4) \
14052 SPIRV_CROSS_THROW("Metal only supports quad ClusteredReduce."); \
14053 emit_unary_func_op(result_type, id, ops[4], "quad_" #msl_op); \
14054 } \
14055 else \
14056 SPIRV_CROSS_THROW("Invalid group operation."); \
14057 break; \
14058 }
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010014059
14060#define MSL_GROUP_OP_CAST(op, msl_op, type) \
14061case OpGroupNonUniform##op: \
14062 { \
14063 auto operation = static_cast<GroupOperation>(ops[3]); \
14064 if (operation == GroupOperationReduce) \
14065 emit_unary_func_op_cast(result_type, id, ops[4], "simd_" #msl_op, type, type); \
14066 else if (operation == GroupOperationInclusiveScan) \
14067 SPIRV_CROSS_THROW("Metal doesn't support InclusiveScan for OpGroupNonUniform" #op "."); \
14068 else if (operation == GroupOperationExclusiveScan) \
14069 SPIRV_CROSS_THROW("Metal doesn't support ExclusiveScan for OpGroupNonUniform" #op "."); \
14070 else if (operation == GroupOperationClusteredReduce) \
14071 { \
14072 /* Only cluster sizes of 4 are supported. */ \
Hans-Kristian Arntzen66afe8c2020-09-14 10:42:31 +020014073 uint32_t cluster_size = evaluate_constant_u32(ops[5]); \
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010014074 if (cluster_size != 4) \
14075 SPIRV_CROSS_THROW("Metal only supports quad ClusteredReduce."); \
14076 emit_unary_func_op_cast(result_type, id, ops[4], "quad_" #msl_op, type, type); \
14077 } \
14078 else \
14079 SPIRV_CROSS_THROW("Invalid group operation."); \
14080 break; \
14081 }
14082
Chip Davis9d941572019-05-15 16:03:30 -050014083 MSL_GROUP_OP(FMin, min)
14084 MSL_GROUP_OP(FMax, max)
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010014085 MSL_GROUP_OP_CAST(SMin, min, int_type)
14086 MSL_GROUP_OP_CAST(SMax, max, int_type)
14087 MSL_GROUP_OP_CAST(UMin, min, uint_type)
14088 MSL_GROUP_OP_CAST(UMax, max, uint_type)
Chip Davis9d941572019-05-15 16:03:30 -050014089 MSL_GROUP_OP(BitwiseAnd, and)
14090 MSL_GROUP_OP(BitwiseOr, or)
14091 MSL_GROUP_OP(BitwiseXor, xor)
14092 MSL_GROUP_OP(LogicalAnd, and)
14093 MSL_GROUP_OP(LogicalOr, or)
14094 MSL_GROUP_OP(LogicalXor, xor)
14095 // clang-format on
Hans-Kristian Arntzen2bbb0122020-01-09 12:28:16 +010014096#undef MSL_GROUP_OP
14097#undef MSL_GROUP_OP_CAST
Chip Davis9d941572019-05-15 16:03:30 -050014098
14099 case OpGroupNonUniformQuadSwap:
Chip Davis1264e272020-10-21 01:51:48 -050014100 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvQuadSwap");
Chip Davis9d941572019-05-15 16:03:30 -050014101 break;
Chip Davis9d941572019-05-15 16:03:30 -050014102
14103 case OpGroupNonUniformQuadBroadcast:
Chip Davis1264e272020-10-21 01:51:48 -050014104 emit_binary_func_op(result_type, id, ops[3], ops[4], "spvQuadBroadcast");
Chip Davis9d941572019-05-15 16:03:30 -050014105 break;
14106
14107 default:
14108 SPIRV_CROSS_THROW("Invalid opcode for subgroup.");
14109 }
14110
14111 register_control_dependent_expression(id);
14112}
14113
Bill Hollings1f838562017-06-15 15:24:22 -040014114string CompilerMSL::bitcast_glsl_op(const SPIRType &out_type, const SPIRType &in_type)
Bill Hollings8f6df772017-05-19 18:14:08 -040014115{
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +010014116 if (out_type.basetype == in_type.basetype)
14117 return "";
14118
Chip Davisef0b1fc2019-01-30 20:19:05 -060014119 assert(out_type.basetype != SPIRType::Boolean);
14120 assert(in_type.basetype != SPIRType::Boolean);
14121
Bill Hollingsa75fe072021-08-12 16:19:46 -040014122 bool integral_cast = type_is_integral(out_type) && type_is_integral(in_type) && (out_type.vecsize == in_type.vecsize);
14123 bool same_size_cast = (out_type.width * out_type.vecsize) == (in_type.width * in_type.vecsize);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +010014124
Bill Hollingsa75fe072021-08-12 16:19:46 -040014125 // Bitcasting can only be used between types of the same overall size.
14126 // And always formally cast between integers, because it's trivial, and also
14127 // because Metal can internally cast the results of some integer ops to a larger
14128 // size (eg. short shift right becomes int), which means chaining integer ops
14129 // together may introduce size variations that SPIR-V doesn't know about.
14130 if (same_size_cast && !integral_cast)
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +010014131 {
Bill Hollingsa75fe072021-08-12 16:19:46 -040014132 return "as_type<" + type_to_glsl(out_type) + ">";
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +010014133 }
14134 else
14135 {
Bill Hollingsa75fe072021-08-12 16:19:46 -040014136 return type_to_glsl(out_type);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +010014137 }
Bill Hollings8f6df772017-05-19 18:14:08 -040014138}
14139
Hans-Kristian Arntzen5e5d1c22020-04-21 23:27:33 +020014140bool CompilerMSL::emit_complex_bitcast(uint32_t, uint32_t, uint32_t)
14141{
14142 return false;
14143}
14144
Bill Hollingse73e8e42016-12-17 17:07:53 -050014145// Returns an MSL string identifying the name of a SPIR-V builtin.
14146// Output builtins are qualified with the name of the stage out structure.
Hans-Kristian Arntzenc8d60912017-07-24 10:07:02 +020014147string CompilerMSL::builtin_to_glsl(BuiltIn builtin, StorageClass storage)
Bill Hollings103aabf2016-04-06 17:42:27 -040014148{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014149 switch (builtin)
14150 {
Lukas Hermanns50ac6862019-09-18 14:03:54 -040014151 // Handle HLSL-style 0-based vertex/instance index.
Bill Hollingse73e8e42016-12-17 17:07:53 -050014152 // Override GLSL compiler strictness
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014153 case BuiltInVertexId:
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014154 ensure_builtin(StorageClassInput, BuiltInVertexId);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014155 if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
14156 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014157 {
14158 if (builtin_declaration)
14159 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014160 if (needs_base_vertex_arg != TriState::No)
14161 needs_base_vertex_arg = TriState::Yes;
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014162 return "gl_VertexID";
14163 }
14164 else
14165 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014166 ensure_builtin(StorageClassInput, BuiltInBaseVertex);
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014167 return "(gl_VertexID - gl_BaseVertex)";
14168 }
14169 }
14170 else
14171 {
14172 return "gl_VertexID";
14173 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014174 case BuiltInInstanceId:
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014175 ensure_builtin(StorageClassInput, BuiltInInstanceId);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014176 if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
14177 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014178 {
14179 if (builtin_declaration)
14180 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014181 if (needs_base_instance_arg != TriState::No)
14182 needs_base_instance_arg = TriState::Yes;
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014183 return "gl_InstanceID";
14184 }
14185 else
14186 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014187 ensure_builtin(StorageClassInput, BuiltInBaseInstance);
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014188 return "(gl_InstanceID - gl_BaseInstance)";
14189 }
14190 }
14191 else
14192 {
14193 return "gl_InstanceID";
14194 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014195 case BuiltInVertexIndex:
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014196 ensure_builtin(StorageClassInput, BuiltInVertexIndex);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014197 if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
14198 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014199 {
14200 if (builtin_declaration)
14201 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014202 if (needs_base_vertex_arg != TriState::No)
14203 needs_base_vertex_arg = TriState::Yes;
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014204 return "gl_VertexIndex";
14205 }
14206 else
14207 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014208 ensure_builtin(StorageClassInput, BuiltInBaseVertex);
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014209 return "(gl_VertexIndex - gl_BaseVertex)";
14210 }
14211 }
14212 else
14213 {
14214 return "gl_VertexIndex";
14215 }
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014216 case BuiltInInstanceIndex:
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014217 ensure_builtin(StorageClassInput, BuiltInInstanceIndex);
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014218 if (msl_options.enable_base_index_zero && msl_options.supports_msl_version(1, 1) &&
14219 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014220 {
14221 if (builtin_declaration)
14222 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014223 if (needs_base_instance_arg != TriState::No)
14224 needs_base_instance_arg = TriState::Yes;
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014225 return "gl_InstanceIndex";
14226 }
14227 else
14228 {
Lukas Hermanns9f9276f2019-09-19 14:44:30 -040014229 ensure_builtin(StorageClassInput, BuiltInBaseInstance);
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014230 return "(gl_InstanceIndex - gl_BaseInstance)";
14231 }
14232 }
14233 else
14234 {
14235 return "gl_InstanceIndex";
14236 }
Chip Davisfcad0192018-08-28 13:47:29 -050014237 case BuiltInBaseVertex:
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014238 if (msl_options.supports_msl_version(1, 1) &&
14239 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014240 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014241 needs_base_vertex_arg = TriState::No;
Lukas Hermanns50ac6862019-09-18 14:03:54 -040014242 return "gl_BaseVertex";
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014243 }
14244 else
14245 {
14246 SPIRV_CROSS_THROW("BaseVertex requires Metal 1.1 and Mac or Apple A9+ hardware.");
14247 }
Chip Davisfcad0192018-08-28 13:47:29 -050014248 case BuiltInBaseInstance:
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040014249 if (msl_options.supports_msl_version(1, 1) &&
14250 (msl_options.ios_support_base_vertex_instance || msl_options.is_macos()))
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014251 {
Hans-Kristian Arntzen4ac12592019-10-24 12:41:37 +020014252 needs_base_instance_arg = TriState::No;
Lukas Hermanns50ac6862019-09-18 14:03:54 -040014253 return "gl_BaseInstance";
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014254 }
14255 else
14256 {
14257 SPIRV_CROSS_THROW("BaseInstance requires Metal 1.1 and Mac or Apple A9+ hardware.");
14258 }
Chip Davisfcad0192018-08-28 13:47:29 -050014259 case BuiltInDrawIndex:
Chip Davis2ee8ebb2018-08-29 12:05:33 -050014260 SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
Bill Hollingse73e8e42016-12-17 17:07:53 -050014261
Bill Hollingsf591bc02017-06-30 19:10:46 -040014262 // When used in the entry function, output builtins are qualified with output struct name.
Bill Hollings2964e322018-02-13 14:44:40 -050014263 // Test storage class as NOT Input, as output builtins might be part of generic type.
Chip Davise75add42019-02-05 18:13:26 -060014264 // Also don't do this for tessellation control shaders.
Chip Davis0e9ad142018-09-12 18:00:17 -050014265 case BuiltInViewportIndex:
14266 if (!msl_options.supports_msl_version(2, 0))
14267 SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
14268 /* fallthrough */
Chip Davisb29f83c2020-04-10 01:13:33 -050014269 case BuiltInFragDepth:
14270 case BuiltInFragStencilRefEXT:
14271 if ((builtin == BuiltInFragDepth && !msl_options.enable_frag_depth_builtin) ||
14272 (builtin == BuiltInFragStencilRefEXT && !msl_options.enable_frag_stencil_ref_builtin))
14273 break;
14274 /* fallthrough */
Bill Hollingse73e8e42016-12-17 17:07:53 -050014275 case BuiltInPosition:
14276 case BuiltInPointSize:
14277 case BuiltInClipDistance:
Bill Hollings27d4af72018-01-08 16:18:34 -050014278 case BuiltInCullDistance:
Vadim Shcherbakovdb402232017-12-13 13:02:03 +030014279 case BuiltInLayer:
Bill Hollingsebb50982021-07-13 21:22:13 -040014280 if (get_execution_model() == ExecutionModelTessellationControl)
14281 break;
14282 if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
14283 !is_stage_output_builtin_masked(builtin))
14284 return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
14285 break;
14286
Bill Hollings2964e322018-02-13 14:44:40 -050014287 case BuiltInSampleMask:
Bill Hollingsebb50982021-07-13 21:22:13 -040014288 if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
14289 (has_additional_fixed_sample_mask() || needs_sample_id))
14290 {
14291 string samp_mask_in;
14292 samp_mask_in += "(" + CompilerGLSL::builtin_to_glsl(builtin, storage);
14293 if (has_additional_fixed_sample_mask())
14294 samp_mask_in += " & " + additional_fixed_sample_mask_str();
14295 if (needs_sample_id)
14296 samp_mask_in += " & (1 << gl_SampleID)";
14297 samp_mask_in += ")";
14298 return samp_mask_in;
14299 }
Hans-Kristian Arntzen2a2d57d2021-03-25 18:08:49 +010014300 if (storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point) &&
14301 !is_stage_output_builtin_masked(builtin))
Hans-Kristian Arntzenc8d60912017-07-24 10:07:02 +020014302 return stage_out_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
Bill Hollings2964e322018-02-13 14:44:40 -050014303 break;
Bill Hollingse73e8e42016-12-17 17:07:53 -050014304
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014305 case BuiltInBaryCoordNV:
14306 case BuiltInBaryCoordNoPerspNV:
14307 if (storage == StorageClassInput && current_function && (current_function->self == ir.default_entry_point))
14308 return stage_in_var_name + "." + CompilerGLSL::builtin_to_glsl(builtin, storage);
14309 break;
14310
Chip Daviseb89c3a2019-02-03 23:58:46 -060014311 case BuiltInTessLevelOuter:
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +020014312 if (get_execution_model() == ExecutionModelTessellationControl &&
14313 storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point))
Chip Davisf3c09422019-02-22 12:11:17 -060014314 {
Chip Daviseb89c3a2019-02-03 23:58:46 -060014315 return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
14316 "].edgeTessellationFactor");
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +020014317 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060014318 break;
14319
14320 case BuiltInTessLevelInner:
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +020014321 if (get_execution_model() == ExecutionModelTessellationControl &&
14322 storage != StorageClassInput && current_function && (current_function->self == ir.default_entry_point))
Chip Davisf3c09422019-02-22 12:11:17 -060014323 {
Chip Daviseb89c3a2019-02-03 23:58:46 -060014324 return join(tess_factor_buffer_var_name, "[", to_expression(builtin_primitive_id_id),
14325 "].insideTessellationFactor");
Hans-Kristian Arntzen82a77e52021-04-23 12:40:24 +020014326 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060014327 break;
14328
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014329 default:
Bill Hollings2964e322018-02-13 14:44:40 -050014330 break;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014331 }
Bill Hollings2964e322018-02-13 14:44:40 -050014332
14333 return CompilerGLSL::builtin_to_glsl(builtin, storage);
Bill Hollings103aabf2016-04-06 17:42:27 -040014334}
14335
14336// Returns an MSL string attribute qualifer for a SPIR-V builtin
14337string CompilerMSL::builtin_qualifier(BuiltIn builtin)
14338{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +020014339 auto &execution = get_entry_point();
14340
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014341 switch (builtin)
14342 {
14343 // Vertex function in
14344 case BuiltInVertexId:
14345 return "vertex_id";
14346 case BuiltInVertexIndex:
14347 return "vertex_id";
Chip Davisfcad0192018-08-28 13:47:29 -050014348 case BuiltInBaseVertex:
14349 return "base_vertex";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014350 case BuiltInInstanceId:
14351 return "instance_id";
14352 case BuiltInInstanceIndex:
14353 return "instance_id";
Chip Davisfcad0192018-08-28 13:47:29 -050014354 case BuiltInBaseInstance:
14355 return "base_instance";
14356 case BuiltInDrawIndex:
Chip Davis97d01b62018-08-29 10:18:32 -050014357 SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
Bill Hollings103aabf2016-04-06 17:42:27 -040014358
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014359 // Vertex function out
14360 case BuiltInClipDistance:
14361 return "clip_distance";
14362 case BuiltInPointSize:
14363 return "point_size";
14364 case BuiltInPosition:
Hans-Kristian Arntzena7b2ba22019-06-11 11:31:29 +020014365 if (position_invariant)
14366 {
14367 if (!msl_options.supports_msl_version(2, 1))
14368 SPIRV_CROSS_THROW("Invariant position is only supported on MSL 2.1 and up.");
14369 return "position, invariant";
14370 }
14371 else
14372 return "position";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014373 case BuiltInLayer:
14374 return "render_target_array_index";
Chip Davis0e9ad142018-09-12 18:00:17 -050014375 case BuiltInViewportIndex:
14376 if (!msl_options.supports_msl_version(2, 0))
14377 SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
14378 return "viewport_array_index";
Bill Hollings103aabf2016-04-06 17:42:27 -040014379
Chip Daviseb89c3a2019-02-03 23:58:46 -060014380 // Tess. control function in
14381 case BuiltInInvocationId:
Chip Davis688c5fc2020-02-20 21:38:28 -060014382 if (msl_options.multi_patch_workgroup)
14383 {
14384 // Shouldn't be reached.
14385 SPIRV_CROSS_THROW("InvocationId is computed manually with multi-patch workgroups in MSL.");
14386 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060014387 return "thread_index_in_threadgroup";
14388 case BuiltInPatchVertices:
14389 // Shouldn't be reached.
14390 SPIRV_CROSS_THROW("PatchVertices is derived from the auxiliary buffer in MSL.");
14391 case BuiltInPrimitiveId:
Chip Davise75add42019-02-05 18:13:26 -060014392 switch (execution.model)
14393 {
14394 case ExecutionModelTessellationControl:
Chip Davis688c5fc2020-02-20 21:38:28 -060014395 if (msl_options.multi_patch_workgroup)
14396 {
14397 // Shouldn't be reached.
14398 SPIRV_CROSS_THROW("PrimitiveId is computed manually with multi-patch workgroups in MSL.");
14399 }
Chip Davise75add42019-02-05 18:13:26 -060014400 return "threadgroup_position_in_grid";
14401 case ExecutionModelTessellationEvaluation:
14402 return "patch_id";
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014403 case ExecutionModelFragment:
Chip Davis88e25e62020-11-14 01:57:11 -060014404 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
14405 SPIRV_CROSS_THROW("PrimitiveId on iOS requires MSL 2.3.");
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014406 else if (msl_options.is_macos() && !msl_options.supports_msl_version(2, 2))
14407 SPIRV_CROSS_THROW("PrimitiveId on macOS requires MSL 2.2.");
14408 return "primitive_id";
Chip Davise75add42019-02-05 18:13:26 -060014409 default:
14410 SPIRV_CROSS_THROW("PrimitiveId is not supported in this execution model.");
14411 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060014412
14413 // Tess. control function out
14414 case BuiltInTessLevelOuter:
14415 case BuiltInTessLevelInner:
14416 // Shouldn't be reached.
14417 SPIRV_CROSS_THROW("Tessellation levels are handled specially in MSL.");
14418
Chip Davise75add42019-02-05 18:13:26 -060014419 // Tess. evaluation function in
14420 case BuiltInTessCoord:
14421 return "position_in_patch";
14422
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014423 // Fragment function in
14424 case BuiltInFrontFacing:
14425 return "front_facing";
14426 case BuiltInPointCoord:
14427 return "point_coord";
Bill Hollings8f2dec32016-07-04 11:49:46 -040014428 case BuiltInFragCoord:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014429 return "position";
14430 case BuiltInSampleId:
14431 return "sample_id";
14432 case BuiltInSampleMask:
14433 return "sample_mask";
Chip Davis39bc1012018-09-12 14:05:52 -050014434 case BuiltInSamplePosition:
14435 // Shouldn't be reached.
14436 SPIRV_CROSS_THROW("Sample position is retrieved by a function in MSL.");
Chip Davis7eecf5a2019-05-31 12:06:20 -050014437 case BuiltInViewIndex:
14438 if (execution.model != ExecutionModelFragment)
14439 SPIRV_CROSS_THROW("ViewIndex is handled specially outside fragment shaders.");
14440 // The ViewIndex was implicitly used in the prior stages to set the render_target_array_index,
14441 // so we can get it from there.
14442 return "render_target_array_index";
Bill Hollings103aabf2016-04-06 17:42:27 -040014443
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014444 // Fragment function out
14445 case BuiltInFragDepth:
Hans-Kristian Arntzene8e58842018-03-12 13:09:25 +010014446 if (execution.flags.get(ExecutionModeDepthGreater))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014447 return "depth(greater)";
Hans-Kristian Arntzene8e58842018-03-12 13:09:25 +010014448 else if (execution.flags.get(ExecutionModeDepthLess))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014449 return "depth(less)";
Hans-Kristian Arntzen3c404c42017-06-17 09:35:42 +020014450 else
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014451 return "depth(any)";
Bill Hollings103aabf2016-04-06 17:42:27 -040014452
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020014453 case BuiltInFragStencilRefEXT:
14454 return "stencil";
14455
Corentin Wallez789eb432017-01-26 19:40:56 -050014456 // Compute function in
Corentin Wallez6d653aa2017-01-22 13:09:04 -050014457 case BuiltInGlobalInvocationId:
14458 return "thread_position_in_grid";
14459
Hans-Kristian Arntzenaab31072017-09-29 12:16:53 +020014460 case BuiltInWorkgroupId:
14461 return "threadgroup_position_in_grid";
14462
14463 case BuiltInNumWorkgroups:
14464 return "threadgroups_per_grid";
14465
Corentin Wallezd8278a82017-01-26 20:22:31 -050014466 case BuiltInLocalInvocationId:
14467 return "thread_position_in_threadgroup";
14468
14469 case BuiltInLocalInvocationIndex:
14470 return "thread_index_in_threadgroup";
14471
Chip Davis9d941572019-05-15 16:03:30 -050014472 case BuiltInSubgroupSize:
Chip Davis68908352020-11-18 23:16:46 -060014473 if (msl_options.emulate_subgroups || msl_options.fixed_subgroup_size != 0)
14474 // Shouldn't be reached.
14475 SPIRV_CROSS_THROW("Emitting threads_per_simdgroup attribute with fixed subgroup size??");
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020014476 if (execution.model == ExecutionModelFragment)
14477 {
14478 if (!msl_options.supports_msl_version(2, 2))
14479 SPIRV_CROSS_THROW("threads_per_simdgroup requires Metal 2.2 in fragment shaders.");
14480 return "threads_per_simdgroup";
14481 }
14482 else
14483 {
14484 // thread_execution_width is an alias for threads_per_simdgroup, and it's only available since 1.0,
14485 // but not in fragment.
14486 return "thread_execution_width";
14487 }
Chip Davis9d941572019-05-15 16:03:30 -050014488
14489 case BuiltInNumSubgroups:
Chip Davis68908352020-11-18 23:16:46 -060014490 if (msl_options.emulate_subgroups)
14491 // Shouldn't be reached.
14492 SPIRV_CROSS_THROW("NumSubgroups is handled specially with emulation.");
Chip Davis9d941572019-05-15 16:03:30 -050014493 if (!msl_options.supports_msl_version(2))
14494 SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
14495 return msl_options.is_ios() ? "quadgroups_per_threadgroup" : "simdgroups_per_threadgroup";
14496
14497 case BuiltInSubgroupId:
Chip Davis68908352020-11-18 23:16:46 -060014498 if (msl_options.emulate_subgroups)
14499 // Shouldn't be reached.
14500 SPIRV_CROSS_THROW("SubgroupId is handled specially with emulation.");
Chip Davis9d941572019-05-15 16:03:30 -050014501 if (!msl_options.supports_msl_version(2))
14502 SPIRV_CROSS_THROW("Subgroup builtins require Metal 2.0.");
14503 return msl_options.is_ios() ? "quadgroup_index_in_threadgroup" : "simdgroup_index_in_threadgroup";
14504
14505 case BuiltInSubgroupLocalInvocationId:
Chip Davis68908352020-11-18 23:16:46 -060014506 if (msl_options.emulate_subgroups)
14507 // Shouldn't be reached.
14508 SPIRV_CROSS_THROW("SubgroupLocalInvocationId is handled specially with emulation.");
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020014509 if (execution.model == ExecutionModelFragment)
14510 {
14511 if (!msl_options.supports_msl_version(2, 2))
14512 SPIRV_CROSS_THROW("thread_index_in_simdgroup requires Metal 2.2 in fragment shaders.");
14513 return "thread_index_in_simdgroup";
14514 }
comex5a85fa92020-11-26 17:12:06 -050014515 else if (execution.model == ExecutionModelKernel || execution.model == ExecutionModelGLCompute ||
14516 execution.model == ExecutionModelTessellationControl ||
14517 (execution.model == ExecutionModelVertex && msl_options.vertex_for_tessellation))
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020014518 {
comex5a85fa92020-11-26 17:12:06 -050014519 // We are generating a Metal kernel function.
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020014520 if (!msl_options.supports_msl_version(2))
comex5a85fa92020-11-26 17:12:06 -050014521 SPIRV_CROSS_THROW("Subgroup builtins in kernel functions require Metal 2.0.");
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020014522 return msl_options.is_ios() ? "thread_index_in_quadgroup" : "thread_index_in_simdgroup";
14523 }
comex5a85fa92020-11-26 17:12:06 -050014524 else
14525 SPIRV_CROSS_THROW("Subgroup builtins are not available in this type of function.");
Chip Davis9d941572019-05-15 16:03:30 -050014526
14527 case BuiltInSubgroupEqMask:
14528 case BuiltInSubgroupGeMask:
14529 case BuiltInSubgroupGtMask:
14530 case BuiltInSubgroupLeMask:
14531 case BuiltInSubgroupLtMask:
14532 // Shouldn't be reached.
14533 SPIRV_CROSS_THROW("Subgroup ballot masks are handled specially in MSL.");
14534
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014535 case BuiltInBaryCoordNV:
14536 // TODO: AMD barycentrics as well? Seem to have different swizzle and 2 components rather than 3.
Chip Davis88e25e62020-11-14 01:57:11 -060014537 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
14538 SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.3 and above on iOS.");
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014539 else if (!msl_options.supports_msl_version(2, 2))
14540 SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.2 and above on macOS.");
14541 return "barycentric_coord, center_perspective";
14542
14543 case BuiltInBaryCoordNoPerspNV:
14544 // TODO: AMD barycentrics as well? Seem to have different swizzle and 2 components rather than 3.
Chip Davis88e25e62020-11-14 01:57:11 -060014545 if (msl_options.is_ios() && !msl_options.supports_msl_version(2, 3))
14546 SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.3 and above on iOS.");
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014547 else if (!msl_options.supports_msl_version(2, 2))
14548 SPIRV_CROSS_THROW("Barycentrics are only supported in MSL 2.2 and above on macOS.");
14549 return "barycentric_coord, center_no_perspective";
14550
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014551 default:
14552 return "unsupported-built-in";
14553 }
Bill Hollings103aabf2016-04-06 17:42:27 -040014554}
14555
14556// Returns an MSL string type declaration for a SPIR-V builtin
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014557string CompilerMSL::builtin_type_decl(BuiltIn builtin, uint32_t id)
Bill Hollings103aabf2016-04-06 17:42:27 -040014558{
Chip Davisf3c09422019-02-22 12:11:17 -060014559 const SPIREntryPoint &execution = get_entry_point();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014560 switch (builtin)
14561 {
14562 // Vertex function in
14563 case BuiltInVertexId:
14564 return "uint";
14565 case BuiltInVertexIndex:
14566 return "uint";
Chip Davisfcad0192018-08-28 13:47:29 -050014567 case BuiltInBaseVertex:
14568 return "uint";
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014569 case BuiltInInstanceId:
14570 return "uint";
14571 case BuiltInInstanceIndex:
14572 return "uint";
Chip Davisfcad0192018-08-28 13:47:29 -050014573 case BuiltInBaseInstance:
14574 return "uint";
14575 case BuiltInDrawIndex:
Chip Davis97d01b62018-08-29 10:18:32 -050014576 SPIRV_CROSS_THROW("DrawIndex is not supported in MSL.");
Bill Hollings103aabf2016-04-06 17:42:27 -040014577
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014578 // Vertex function out
14579 case BuiltInClipDistance:
Hans-Kristian Arntzen682a2272021-04-16 12:18:31 +020014580 case BuiltInCullDistance:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014581 return "float";
14582 case BuiltInPointSize:
14583 return "float";
14584 case BuiltInPosition:
14585 return "float4";
Vadim Shcherbakovdb402232017-12-13 13:02:03 +030014586 case BuiltInLayer:
14587 return "uint";
Chip Davis0e9ad142018-09-12 18:00:17 -050014588 case BuiltInViewportIndex:
14589 if (!msl_options.supports_msl_version(2, 0))
14590 SPIRV_CROSS_THROW("ViewportIndex requires Metal 2.0.");
14591 return "uint";
Bill Hollings103aabf2016-04-06 17:42:27 -040014592
Chip Daviseb89c3a2019-02-03 23:58:46 -060014593 // Tess. control function in
14594 case BuiltInInvocationId:
14595 return "uint";
14596 case BuiltInPatchVertices:
14597 return "uint";
14598 case BuiltInPrimitiveId:
14599 return "uint";
14600
14601 // Tess. control function out
14602 case BuiltInTessLevelInner:
Chip Davisf3c09422019-02-22 12:11:17 -060014603 if (execution.model == ExecutionModelTessellationEvaluation)
14604 return !execution.flags.get(ExecutionModeTriangles) ? "float2" : "float";
Chip Daviseb89c3a2019-02-03 23:58:46 -060014605 return "half";
14606 case BuiltInTessLevelOuter:
Chip Davisf3c09422019-02-22 12:11:17 -060014607 if (execution.model == ExecutionModelTessellationEvaluation)
14608 return !execution.flags.get(ExecutionModeTriangles) ? "float4" : "float";
Chip Daviseb89c3a2019-02-03 23:58:46 -060014609 return "half";
14610
Chip Davise75add42019-02-05 18:13:26 -060014611 // Tess. evaluation function in
14612 case BuiltInTessCoord:
Nikita Fediuchin2acf0e72021-12-20 22:58:21 +020014613 return "float3";
Chip Davise75add42019-02-05 18:13:26 -060014614
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014615 // Fragment function in
14616 case BuiltInFrontFacing:
14617 return "bool";
14618 case BuiltInPointCoord:
14619 return "float2";
Bill Hollings8f2dec32016-07-04 11:49:46 -040014620 case BuiltInFragCoord:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014621 return "float4";
14622 case BuiltInSampleId:
14623 return "uint";
14624 case BuiltInSampleMask:
14625 return "uint";
Chip Davis39bc1012018-09-12 14:05:52 -050014626 case BuiltInSamplePosition:
14627 return "float2";
Chip Davis7eecf5a2019-05-31 12:06:20 -050014628 case BuiltInViewIndex:
14629 return "uint";
Bill Hollings103aabf2016-04-06 17:42:27 -040014630
Chip Davis6a585542019-07-12 21:50:50 -050014631 case BuiltInHelperInvocation:
14632 return "bool";
14633
14634 case BuiltInBaryCoordNV:
14635 case BuiltInBaryCoordNoPerspNV:
14636 // Use the type as declared, can be 1, 2 or 3 components.
14637 return type_to_glsl(get_variable_data_type(get<SPIRVariable>(id)));
14638
Chip Davis1fd8cd92018-08-28 13:47:50 -050014639 // Fragment function out
14640 case BuiltInFragDepth:
14641 return "float";
14642
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020014643 case BuiltInFragStencilRefEXT:
14644 return "uint";
14645
Corentin Wallez6d653aa2017-01-22 13:09:04 -050014646 // Compute function in
14647 case BuiltInGlobalInvocationId:
Corentin Wallezd8278a82017-01-26 20:22:31 -050014648 case BuiltInLocalInvocationId:
Hans-Kristian Arntzenaab31072017-09-29 12:16:53 +020014649 case BuiltInNumWorkgroups:
14650 case BuiltInWorkgroupId:
Corentin Wallezd8278a82017-01-26 20:22:31 -050014651 return "uint3";
14652 case BuiltInLocalInvocationIndex:
Chip Davis9d941572019-05-15 16:03:30 -050014653 case BuiltInNumSubgroups:
14654 case BuiltInSubgroupId:
14655 case BuiltInSubgroupSize:
14656 case BuiltInSubgroupLocalInvocationId:
Corentin Wallezd8278a82017-01-26 20:22:31 -050014657 return "uint";
Chip Davis9d941572019-05-15 16:03:30 -050014658 case BuiltInSubgroupEqMask:
14659 case BuiltInSubgroupGeMask:
14660 case BuiltInSubgroupGtMask:
14661 case BuiltInSubgroupLeMask:
14662 case BuiltInSubgroupLtMask:
14663 return "uint4";
Corentin Wallez6d653aa2017-01-22 13:09:04 -050014664
Chip Davis6a585542019-07-12 21:50:50 -050014665 case BuiltInDeviceIndex:
14666 return "int";
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020014667
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020014668 default:
14669 return "unsupported-built-in-type";
14670 }
Bill Hollings103aabf2016-04-06 17:42:27 -040014671}
14672
Bill Hollings81757502017-01-29 13:28:20 -050014673// Returns the declaration of a built-in argument to a function
14674string CompilerMSL::built_in_func_arg(BuiltIn builtin, bool prefix_comma)
14675{
14676 string bi_arg;
14677 if (prefix_comma)
14678 bi_arg += ", ";
Hans-Kristian Arntzenc8d60912017-07-24 10:07:02 +020014679
Lukas Hermanns50ac6862019-09-18 14:03:54 -040014680 // Handle HLSL-style 0-based vertex/instance index.
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014681 builtin_declaration = true;
Bill Hollings1c180782017-11-05 21:34:42 -050014682 bi_arg += builtin_type_decl(builtin);
Hans-Kristian Arntzenc8d60912017-07-24 10:07:02 +020014683 bi_arg += " " + builtin_to_glsl(builtin, StorageClassInput);
Bill Hollings81757502017-01-29 13:28:20 -050014684 bi_arg += " [[" + builtin_qualifier(builtin) + "]]";
Mark Satterthwaitede6441a2019-08-14 10:50:36 -040014685 builtin_declaration = false;
Bill Hollings86a9a402017-09-03 22:55:54 -040014686
Bill Hollings1c180782017-11-05 21:34:42 -050014687 return bi_arg;
Bill Hollings81757502017-01-29 13:28:20 -050014688}
14689
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014690const SPIRType &CompilerMSL::get_physical_member_type(const SPIRType &type, uint32_t index) const
14691{
14692 if (member_is_remapped_physical_type(type, index))
14693 return get<SPIRType>(get_extended_member_decoration(type.self, index, SPIRVCrossDecorationPhysicalTypeID));
14694 else
14695 return get<SPIRType>(type.member_types[index]);
14696}
14697
Chip Davis688c5fc2020-02-20 21:38:28 -060014698SPIRType CompilerMSL::get_presumed_input_type(const SPIRType &ib_type, uint32_t index) const
14699{
14700 SPIRType type = get_physical_member_type(ib_type, index);
14701 uint32_t loc = get_member_decoration(ib_type.self, index, DecorationLocation);
Bill Hollings548a23d2021-09-20 17:57:11 -040014702 uint32_t cmp = get_member_decoration(ib_type.self, index, DecorationComponent);
14703 auto p_va = inputs_by_location.find({loc, cmp});
14704 if (p_va != end(inputs_by_location) && p_va->second.vecsize > type.vecsize)
14705 type.vecsize = p_va->second.vecsize;
14706
Chip Davis688c5fc2020-02-20 21:38:28 -060014707 return type;
14708}
14709
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +020014710uint32_t CompilerMSL::get_declared_type_array_stride_msl(const SPIRType &type, bool is_packed, bool row_major) const
Bill Hollings103aabf2016-04-06 17:42:27 -040014711{
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014712 // Array stride in MSL is always size * array_size. sizeof(float3) == 16,
14713 // unlike GLSL and HLSL where array stride would be 16 and size 12.
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +020014714
14715 // We could use parent type here and recurse, but that makes creating physical type remappings
14716 // far more complicated. We'd rather just create the final type, and ignore having to create the entire type
14717 // hierarchy in order to compute this value, so make a temporary type on the stack.
14718
14719 auto basic_type = type;
14720 basic_type.array.clear();
14721 basic_type.array_size_literal.clear();
14722 uint32_t value_size = get_declared_type_size_msl(basic_type, is_packed, row_major);
14723
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +020014724 uint32_t dimensions = uint32_t(type.array.size());
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +020014725 assert(dimensions > 0);
14726 dimensions--;
14727
14728 // Multiply together every dimension, except the last one.
14729 for (uint32_t dim = 0; dim < dimensions; dim++)
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014730 {
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +020014731 uint32_t array_size = to_array_size_literal(type, dim);
14732 value_size *= max(array_size, 1u);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014733 }
Hans-Kristian Arntzenf6251e42019-07-19 11:21:02 +020014734
14735 return value_size;
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014736}
Bill Hollingse73e8e42016-12-17 17:07:53 -050014737
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014738uint32_t CompilerMSL::get_declared_struct_member_array_stride_msl(const SPIRType &type, uint32_t index) const
14739{
14740 return get_declared_type_array_stride_msl(get_physical_member_type(type, index),
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014741 member_is_packed_physical_type(type, index),
14742 has_member_decoration(type.self, index, DecorationRowMajor));
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014743}
14744
Chip Davis688c5fc2020-02-20 21:38:28 -060014745uint32_t CompilerMSL::get_declared_input_array_stride_msl(const SPIRType &type, uint32_t index) const
14746{
14747 return get_declared_type_array_stride_msl(get_presumed_input_type(type, index), false,
14748 has_member_decoration(type.self, index, DecorationRowMajor));
14749}
14750
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014751uint32_t CompilerMSL::get_declared_type_matrix_stride_msl(const SPIRType &type, bool packed, bool row_major) const
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014752{
14753 // For packed matrices, we just use the size of the vector type.
14754 // Otherwise, MatrixStride == alignment, which is the size of the underlying vector type.
14755 if (packed)
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +020014756 return (type.width / 8) * ((row_major && type.columns > 1) ? type.columns : type.vecsize);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014757 else
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014758 return get_declared_type_alignment_msl(type, false, row_major);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014759}
14760
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014761uint32_t CompilerMSL::get_declared_struct_member_matrix_stride_msl(const SPIRType &type, uint32_t index) const
14762{
14763 return get_declared_type_matrix_stride_msl(get_physical_member_type(type, index),
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014764 member_is_packed_physical_type(type, index),
14765 has_member_decoration(type.self, index, DecorationRowMajor));
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014766}
14767
Chip Davis688c5fc2020-02-20 21:38:28 -060014768uint32_t CompilerMSL::get_declared_input_matrix_stride_msl(const SPIRType &type, uint32_t index) const
14769{
14770 return get_declared_type_matrix_stride_msl(get_presumed_input_type(type, index), false,
14771 has_member_decoration(type.self, index, DecorationRowMajor));
14772}
14773
Hans-Kristian Arntzen3fa2b142019-07-23 12:23:41 +020014774uint32_t CompilerMSL::get_declared_struct_size_msl(const SPIRType &struct_type, bool ignore_alignment,
14775 bool ignore_padding) const
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014776{
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020014777 // If we have a target size, that is the declared size as well.
14778 if (!ignore_padding && has_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget))
14779 return get_extended_decoration(struct_type.self, SPIRVCrossDecorationPaddingTarget);
14780
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014781 if (struct_type.member_types.empty())
14782 return 0;
14783
Hans-Kristian Arntzen646e0422019-07-23 16:39:13 +020014784 uint32_t mbr_cnt = uint32_t(struct_type.member_types.size());
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014785
14786 // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
14787 uint32_t alignment = 1;
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020014788
14789 if (!ignore_alignment)
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014790 {
Hans-Kristian Arntzenbe2fccd2019-07-22 10:23:39 +020014791 for (uint32_t i = 0; i < mbr_cnt; i++)
14792 {
14793 uint32_t mbr_alignment = get_declared_struct_member_alignment_msl(struct_type, i);
14794 alignment = max(alignment, mbr_alignment);
14795 }
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014796 }
14797
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014798 // Last member will always be matched to the final Offset decoration, but size of struct in MSL now depends
14799 // on physical size in MSL, and the size of the struct itself is then aligned to struct alignment.
14800 uint32_t spirv_offset = type_struct_member_offset(struct_type, mbr_cnt - 1);
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014801 uint32_t msl_size = spirv_offset + get_declared_struct_member_size_msl(struct_type, mbr_cnt - 1);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014802 msl_size = (msl_size + alignment - 1) & ~(alignment - 1);
14803 return msl_size;
14804}
14805
14806// Returns the byte size of a struct member.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014807uint32_t CompilerMSL::get_declared_type_size_msl(const SPIRType &type, bool is_packed, bool row_major) const
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014808{
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014809 switch (type.basetype)
14810 {
14811 case SPIRType::Unknown:
14812 case SPIRType::Void:
14813 case SPIRType::AtomicCounter:
14814 case SPIRType::Image:
14815 case SPIRType::SampledImage:
14816 case SPIRType::Sampler:
14817 SPIRV_CROSS_THROW("Querying size of opaque object.");
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014818
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014819 default:
14820 {
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014821 if (!type.array.empty())
Hans-Kristian Arntzendd603ea2018-02-23 15:09:28 +010014822 {
Hans-Kristian Arntzen480acda2018-11-01 14:56:25 +010014823 uint32_t array_size = to_array_size_literal(type);
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014824 return get_declared_type_array_stride_msl(type, is_packed, row_major) * max(array_size, 1u);
Hans-Kristian Arntzendd603ea2018-02-23 15:09:28 +010014825 }
Bill Hollings1c180782017-11-05 21:34:42 -050014826
14827 if (type.basetype == SPIRType::Struct)
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014828 return get_declared_struct_size_msl(type);
14829
14830 if (is_packed)
Hans-Kristian Arntzen912fde92019-01-28 14:39:05 +010014831 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014832 return type.vecsize * type.columns * (type.width / 8);
Hans-Kristian Arntzen912fde92019-01-28 14:39:05 +010014833 }
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014834 else
14835 {
14836 // An unpacked 3-element vector or matrix column is the same memory size as a 4-element.
14837 uint32_t vecsize = type.vecsize;
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014838 uint32_t columns = type.columns;
14839
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +020014840 if (row_major && columns > 1)
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014841 swap(vecsize, columns);
14842
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014843 if (vecsize == 3)
14844 vecsize = 4;
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014845
Hans-Kristian Arntzen27b75c22019-07-19 12:53:10 +020014846 return vecsize * columns * (type.width / 8);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014847 }
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014848 }
14849 }
14850}
14851
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014852uint32_t CompilerMSL::get_declared_struct_member_size_msl(const SPIRType &type, uint32_t index) const
14853{
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014854 return get_declared_type_size_msl(get_physical_member_type(type, index),
14855 member_is_packed_physical_type(type, index),
14856 has_member_decoration(type.self, index, DecorationRowMajor));
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014857}
14858
Chip Davis688c5fc2020-02-20 21:38:28 -060014859uint32_t CompilerMSL::get_declared_input_size_msl(const SPIRType &type, uint32_t index) const
14860{
14861 return get_declared_type_size_msl(get_presumed_input_type(type, index), false,
14862 has_member_decoration(type.self, index, DecorationRowMajor));
14863}
14864
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014865// Returns the byte alignment of a type.
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014866uint32_t CompilerMSL::get_declared_type_alignment_msl(const SPIRType &type, bool is_packed, bool row_major) const
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014867{
Bill Hollingsac00c602016-10-24 09:24:24 -040014868 switch (type.basetype)
14869 {
14870 case SPIRType::Unknown:
14871 case SPIRType::Void:
14872 case SPIRType::AtomicCounter:
14873 case SPIRType::Image:
14874 case SPIRType::SampledImage:
14875 case SPIRType::Sampler:
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014876 SPIRV_CROSS_THROW("Querying alignment of opaque object.");
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014877
Hans-Kristian Arntzena6798d02019-06-19 10:11:10 +020014878 case SPIRType::Double:
14879 SPIRV_CROSS_THROW("double types are not supported in buffers in MSL.");
14880
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014881 case SPIRType::Struct:
Hans-Kristian Arntzen8c632da2019-01-28 11:02:28 +010014882 {
14883 // In MSL, a struct's alignment is equal to the maximum alignment of any of its members.
14884 uint32_t alignment = 1;
14885 for (uint32_t i = 0; i < type.member_types.size(); i++)
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014886 alignment = max(alignment, uint32_t(get_declared_struct_member_alignment_msl(type, i)));
Hans-Kristian Arntzen8c632da2019-01-28 11:02:28 +010014887 return alignment;
14888 }
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014889
Bill Hollingsac00c602016-10-24 09:24:24 -040014890 default:
Bill Hollingsac00c602016-10-24 09:24:24 -040014891 {
Mehmet Oguz Derine2f7a752021-03-26 16:29:44 +030014892 if (type.basetype == SPIRType::Int64 && !msl_options.supports_msl_version(2, 3))
14893 SPIRV_CROSS_THROW("long types in buffers are only supported in MSL 2.3 and above.");
14894 if (type.basetype == SPIRType::UInt64 && !msl_options.supports_msl_version(2, 3))
14895 SPIRV_CROSS_THROW("ulong types in buffers are only supported in MSL 2.3 and above.");
Bill Hollings607b0d62018-02-11 16:52:57 -050014896 // Alignment of packed type is the same as the underlying component or column size.
14897 // Alignment of unpacked type is the same as the vector size.
14898 // Alignment of 3-elements vector is the same as 4-elements (including packed using column).
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014899 if (is_packed)
Hans-Kristian Arntzen912fde92019-01-28 14:39:05 +010014900 {
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014901 // If we have packed_T and friends, the alignment is always scalar.
14902 return type.width / 8;
Hans-Kristian Arntzen912fde92019-01-28 14:39:05 +010014903 }
Bill Hollingsa3546eb2017-03-06 11:00:23 -050014904 else
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014905 {
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014906 // This is the general rule for MSL. Size == alignment.
Hans-Kristian Arntzen17ad62e2020-04-20 11:02:20 +020014907 uint32_t vecsize = (row_major && type.columns > 1) ? type.columns : type.vecsize;
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014908 return (type.width / 8) * (vecsize == 3 ? 4 : vecsize);
Hans-Kristian Arntzena86308b2019-07-18 13:34:47 +020014909 }
Bill Hollingse73e8e42016-12-17 17:07:53 -050014910 }
Bill Hollings484931d2017-02-28 21:44:36 -050014911 }
Bill Hollings103aabf2016-04-06 17:42:27 -040014912}
14913
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014914uint32_t CompilerMSL::get_declared_struct_member_alignment_msl(const SPIRType &type, uint32_t index) const
14915{
Hans-Kristian Arntzenb09b8d32019-07-18 16:39:25 +020014916 return get_declared_type_alignment_msl(get_physical_member_type(type, index),
14917 member_is_packed_physical_type(type, index),
14918 has_member_decoration(type.self, index, DecorationRowMajor));
Hans-Kristian Arntzenc160d522019-07-18 13:48:27 +020014919}
14920
Chip Davis688c5fc2020-02-20 21:38:28 -060014921uint32_t CompilerMSL::get_declared_input_alignment_msl(const SPIRType &type, uint32_t index) const
14922{
14923 return get_declared_type_alignment_msl(get_presumed_input_type(type, index), false,
14924 has_member_decoration(type.self, index, DecorationRowMajor));
14925}
14926
Hans-Kristian Arntzenf081fe12017-05-07 12:36:14 +020014927bool CompilerMSL::skip_argument(uint32_t) const
14928{
14929 return false;
14930}
14931
Chip Davisc11374c2018-09-24 12:10:27 -050014932void CompilerMSL::analyze_sampled_image_usage()
Chip Davis4302c5a2018-09-22 19:36:11 -050014933{
Chip Davis4302c5a2018-09-22 19:36:11 -050014934 if (msl_options.swizzle_texture_samples)
14935 {
14936 SampledImageScanner scanner(*this);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020014937 traverse_all_reachable_opcodes(get<SPIRFunction>(ir.default_entry_point), scanner);
Chip Davis4302c5a2018-09-22 19:36:11 -050014938 }
14939}
14940
14941bool CompilerMSL::SampledImageScanner::handle(spv::Op opcode, const uint32_t *args, uint32_t length)
14942{
14943 switch (opcode)
14944 {
14945 case OpLoad:
14946 case OpImage:
14947 case OpSampledImage:
14948 {
14949 if (length < 3)
14950 return false;
14951
14952 uint32_t result_type = args[0];
14953 auto &type = compiler.get<SPIRType>(result_type);
14954 if ((type.basetype != SPIRType::Image && type.basetype != SPIRType::SampledImage) || type.image.sampled != 1)
14955 return true;
14956
14957 uint32_t id = args[1];
14958 compiler.set<SPIRExpression>(id, "", result_type, true);
14959 break;
14960 }
14961 case OpImageSampleExplicitLod:
14962 case OpImageSampleProjExplicitLod:
14963 case OpImageSampleDrefExplicitLod:
14964 case OpImageSampleProjDrefExplicitLod:
14965 case OpImageSampleImplicitLod:
14966 case OpImageSampleProjImplicitLod:
14967 case OpImageSampleDrefImplicitLod:
14968 case OpImageSampleProjDrefImplicitLod:
14969 case OpImageFetch:
14970 case OpImageGather:
Chip Davis010fecc2018-09-29 09:52:26 -050014971 case OpImageDrefGather:
Hans-Kristian Arntzenc07c3032018-09-27 13:36:38 +020014972 compiler.has_sampled_images =
14973 compiler.has_sampled_images || compiler.is_sampled_image_type(compiler.expression_type(args[2]));
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020014974 compiler.needs_swizzle_buffer_def = compiler.needs_swizzle_buffer_def || compiler.has_sampled_images;
Chip Davis4302c5a2018-09-22 19:36:11 -050014975 break;
14976 default:
14977 break;
14978 }
14979 return true;
14980}
14981
Chip Davis39dce882019-08-02 15:11:19 -050014982// If a needed custom function wasn't added before, add it and force a recompile.
14983void CompilerMSL::add_spv_func_and_recompile(SPVFuncImpl spv_func)
14984{
14985 if (spv_function_implementations.count(spv_func) == 0)
14986 {
14987 spv_function_implementations.insert(spv_func);
14988 suppress_missing_prototypes = true;
14989 force_recompile();
14990 }
14991}
14992
Bill Hollings1c180782017-11-05 21:34:42 -050014993bool CompilerMSL::OpCodePreprocessor::handle(Op opcode, const uint32_t *args, uint32_t length)
Bill Hollings103aabf2016-04-06 17:42:27 -040014994{
Bill Hollings8f6df772017-05-19 18:14:08 -040014995 // Since MSL exists in a single execution scope, function prototype declarations are not
14996 // needed, and clutter the output. If secondary functions are output (either as a SPIR-V
14997 // function implementation or as indicated by the presence of OpFunctionCall), then set
14998 // suppress_missing_prototypes to suppress compiler warnings of missing function prototypes.
14999
15000 // Mark if the input requires the implementation of an SPIR-V function that does not exist in Metal.
Bill Hollings1c180782017-11-05 21:34:42 -050015001 SPVFuncImpl spv_func = get_spv_func_impl(opcode, args);
Bill Hollings8f6df772017-05-19 18:14:08 -040015002 if (spv_func != SPVFuncImplNone)
15003 {
15004 compiler.spv_function_implementations.insert(spv_func);
15005 suppress_missing_prototypes = true;
Bill Hollings8f6df772017-05-19 18:14:08 -040015006 }
15007
Bill Hollings7d38f182016-12-21 16:31:13 -050015008 switch (opcode)
15009 {
Bill Hollings7d38f182016-12-21 16:31:13 -050015010
Bill Hollings2d0d3282017-01-20 11:33:59 -050015011 case OpFunctionCall:
15012 suppress_missing_prototypes = true;
Bill Hollings7d38f182016-12-21 16:31:13 -050015013 break;
15014
Lukas Hermanns50ac6862019-09-18 14:03:54 -040015015 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015016 case OpImageTexelPointer:
15017 {
15018 auto *var = compiler.maybe_get_backing_variable(args[2]);
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020015019 image_pointers[args[1]] = var ? var->self : ID(0);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015020 break;
15021 }
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040015022
Bill Hollingsac238b82018-07-26 00:50:33 -040015023 case OpImageWrite:
Chip Davis1b6b9702020-10-20 00:54:59 -050015024 if (!compiler.msl_options.supports_msl_version(2, 2))
15025 uses_resource_write = true;
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015026 break;
15027
15028 case OpStore:
15029 check_resource_write(args[0]);
Bill Hollingsac238b82018-07-26 00:50:33 -040015030 break;
15031
Lukas Hermanns50ac6862019-09-18 14:03:54 -040015032 // Emulate texture2D atomic operations
Bill Hollings8f6df772017-05-19 18:14:08 -040015033 case OpAtomicExchange:
15034 case OpAtomicCompareExchange:
15035 case OpAtomicCompareExchangeWeak:
Bill Hollings8f6df772017-05-19 18:14:08 -040015036 case OpAtomicIIncrement:
15037 case OpAtomicIDecrement:
15038 case OpAtomicIAdd:
15039 case OpAtomicISub:
15040 case OpAtomicSMin:
15041 case OpAtomicUMin:
15042 case OpAtomicSMax:
15043 case OpAtomicUMax:
15044 case OpAtomicAnd:
15045 case OpAtomicOr:
15046 case OpAtomicXor:
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015047 {
Bill Hollings8f6df772017-05-19 18:14:08 -040015048 uses_atomics = true;
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015049 auto it = image_pointers.find(args[2]);
15050 if (it != image_pointers.end())
15051 {
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020015052 compiler.atomic_image_vars.insert(it->second);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015053 }
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015054 check_resource_write(args[2]);
15055 break;
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015056 }
15057
15058 case OpAtomicStore:
15059 {
15060 uses_atomics = true;
15061 auto it = image_pointers.find(args[0]);
15062 if (it != image_pointers.end())
15063 {
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020015064 compiler.atomic_image_vars.insert(it->second);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015065 }
15066 check_resource_write(args[0]);
15067 break;
15068 }
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015069
15070 case OpAtomicLoad:
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015071 {
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015072 uses_atomics = true;
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015073 auto it = image_pointers.find(args[2]);
15074 if (it != image_pointers.end())
15075 {
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020015076 compiler.atomic_image_vars.insert(it->second);
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015077 }
Bill Hollings8f6df772017-05-19 18:14:08 -040015078 break;
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015079 }
Bill Hollings8f6df772017-05-19 18:14:08 -040015080
Chip Davis9d941572019-05-15 16:03:30 -050015081 case OpGroupNonUniformInverseBallot:
15082 needs_subgroup_invocation_id = true;
15083 break;
15084
Chip Davis065b5bd2020-10-20 23:59:30 -050015085 case OpGroupNonUniformBallotFindLSB:
15086 case OpGroupNonUniformBallotFindMSB:
15087 needs_subgroup_size = true;
15088 break;
15089
Chip Davis9d941572019-05-15 16:03:30 -050015090 case OpGroupNonUniformBallotBitCount:
Chip Davis065b5bd2020-10-20 23:59:30 -050015091 if (args[3] == GroupOperationReduce)
15092 needs_subgroup_size = true;
15093 else
Chip Davis9d941572019-05-15 16:03:30 -050015094 needs_subgroup_invocation_id = true;
15095 break;
15096
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015097 case OpArrayLength:
15098 {
15099 auto *var = compiler.maybe_get_backing_variable(args[2]);
15100 if (var)
15101 compiler.buffers_requiring_array_length.insert(var->self);
15102 break;
15103 }
15104
15105 case OpInBoundsAccessChain:
15106 case OpAccessChain:
15107 case OpPtrAccessChain:
15108 {
15109 // OpArrayLength might want to know if taking ArrayLength of an array of SSBOs.
15110 uint32_t result_type = args[0];
15111 uint32_t id = args[1];
15112 uint32_t ptr = args[2];
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040015113
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015114 compiler.set<SPIRExpression>(id, "", result_type, true);
15115 compiler.register_read(id, ptr, true);
15116 compiler.ir.ids[id].set_allow_type_rewrite();
15117 break;
15118 }
15119
Chip Davisaca9b682020-11-02 20:56:46 -060015120 case OpExtInst:
15121 {
15122 uint32_t extension_set = args[2];
15123 if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
15124 {
15125 auto op_450 = static_cast<GLSLstd450>(args[3]);
15126 switch (op_450)
15127 {
15128 case GLSLstd450InterpolateAtCentroid:
15129 case GLSLstd450InterpolateAtSample:
15130 case GLSLstd450InterpolateAtOffset:
15131 {
15132 if (!compiler.msl_options.supports_msl_version(2, 3))
15133 SPIRV_CROSS_THROW("Pull-model interpolation requires MSL 2.3.");
15134 // Fragment varyings used with pull-model interpolation need special handling,
15135 // due to the way pull-model interpolation works in Metal.
15136 auto *var = compiler.maybe_get_backing_variable(args[4]);
15137 if (var)
15138 {
15139 compiler.pull_model_inputs.insert(var->self);
15140 auto &var_type = compiler.get_variable_element_type(*var);
15141 // In addition, if this variable has a 'Sample' decoration, we need the sample ID
15142 // in order to do default interpolation.
15143 if (compiler.has_decoration(var->self, DecorationSample))
15144 {
15145 needs_sample_id = true;
15146 }
15147 else if (var_type.basetype == SPIRType::Struct)
15148 {
15149 // Now we need to check each member and see if it has this decoration.
15150 for (uint32_t i = 0; i < var_type.member_types.size(); ++i)
15151 {
15152 if (compiler.has_member_decoration(var_type.self, i, DecorationSample))
15153 {
15154 needs_sample_id = true;
15155 break;
15156 }
15157 }
15158 }
15159 }
15160 break;
15161 }
15162 default:
15163 break;
15164 }
15165 }
15166 break;
15167 }
15168
Bill Hollings7d38f182016-12-21 16:31:13 -050015169 default:
15170 break;
15171 }
Bill Hollings8f6df772017-05-19 18:14:08 -040015172
Bill Hollings3a7e8a12018-01-04 21:13:38 -050015173 // If it has one, keep track of the instruction's result type, mapped by ID
Hans-Kristian Arntzen7d223b82018-01-18 12:07:10 +010015174 uint32_t result_type, result_id;
15175 if (compiler.instruction_to_result_type(result_type, result_id, opcode, args, length))
15176 result_types[result_id] = result_type;
Bill Hollings1c180782017-11-05 21:34:42 -050015177
Bill Hollings7d38f182016-12-21 16:31:13 -050015178 return true;
15179}
15180
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015181// If the variable is a Uniform or StorageBuffer, mark that a resource has been written to.
15182void CompilerMSL::OpCodePreprocessor::check_resource_write(uint32_t var_id)
15183{
15184 auto *p_var = compiler.maybe_get_backing_variable(var_id);
15185 StorageClass sc = p_var ? p_var->storage : StorageClassMax;
Chip Davis1b6b9702020-10-20 00:54:59 -050015186 if (!compiler.msl_options.supports_msl_version(2, 1) &&
15187 (sc == StorageClassUniform || sc == StorageClassStorageBuffer))
Bill Hollingsc3d74e12018-07-27 16:53:36 -040015188 uses_resource_write = true;
15189}
15190
Bill Hollings8f6df772017-05-19 18:14:08 -040015191// Returns an enumeration of a SPIR-V function that needs to be output for certain Op codes.
Bill Hollings1c180782017-11-05 21:34:42 -050015192CompilerMSL::SPVFuncImpl CompilerMSL::OpCodePreprocessor::get_spv_func_impl(Op opcode, const uint32_t *args)
Bill Hollings8f6df772017-05-19 18:14:08 -040015193{
15194 switch (opcode)
15195 {
15196 case OpFMod:
15197 return SPVFuncImplMod;
15198
Lukas Hermanns51be6012019-09-17 15:10:39 -040015199 case OpFAdd:
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +020015200 case OpFSub:
15201 if (compiler.msl_options.invariant_float_math ||
15202 compiler.has_decoration(args[1], DecorationNoContraction))
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +020015203 {
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +020015204 return opcode == OpFAdd ? SPVFuncImplFAdd : SPVFuncImplFSub;
Hans-Kristian Arntzen38d19822018-09-11 12:58:03 +020015205 }
Bill Hollings4c5142b2018-06-26 17:30:21 -040015206 break;
Lukas Hermanns7ad0a842019-09-23 18:05:04 -040015207
Lukas Hermanns51be6012019-09-17 15:10:39 -040015208 case OpFMul:
15209 case OpOuterProduct:
15210 case OpMatrixTimesVector:
15211 case OpVectorTimesMatrix:
15212 case OpMatrixTimesMatrix:
Hans-Kristian Arntzene47a30e2021-05-07 12:28:08 +020015213 if (compiler.msl_options.invariant_float_math ||
15214 compiler.has_decoration(args[1], DecorationNoContraction))
Lukas Hermanns51be6012019-09-17 15:10:39 -040015215 {
15216 return SPVFuncImplFMul;
15217 }
15218 break;
Bill Hollings8f6df772017-05-19 18:14:08 -040015219
Bill Hollings57420472021-09-23 16:26:02 -040015220 case OpQuantizeToF16:
15221 return SPVFuncImplQuantizeToF16;
15222
Lukas Hermanns51be6012019-09-17 15:10:39 -040015223 case OpTypeArray:
Lukas Hermanns50ac6862019-09-18 14:03:54 -040015224 {
15225 // Allow Metal to use the array<T> template to make arrays a value type
Lukas Hermanns51be6012019-09-17 15:10:39 -040015226 return SPVFuncImplUnsafeArray;
Hans-Kristian Arntzen00ccd592018-02-05 12:37:41 +010015227 }
15228
Lukas Hermanns50ac6862019-09-18 14:03:54 -040015229 // Emulate texture2D atomic operations
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015230 case OpAtomicExchange:
15231 case OpAtomicCompareExchange:
15232 case OpAtomicCompareExchangeWeak:
15233 case OpAtomicIIncrement:
15234 case OpAtomicIDecrement:
15235 case OpAtomicIAdd:
15236 case OpAtomicISub:
15237 case OpAtomicSMin:
15238 case OpAtomicUMin:
15239 case OpAtomicSMax:
15240 case OpAtomicUMax:
15241 case OpAtomicAnd:
15242 case OpAtomicOr:
15243 case OpAtomicXor:
15244 case OpAtomicLoad:
15245 case OpAtomicStore:
Bill Hollings1c180782017-11-05 21:34:42 -050015246 {
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015247 auto it = image_pointers.find(args[opcode == OpAtomicStore ? 0 : 2]);
15248 if (it != image_pointers.end())
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +010015249 {
Hans-Kristian Arntzen6edbf0c2019-10-24 11:30:20 +020015250 uint32_t tid = compiler.get<SPIRVariable>(it->second).basetype;
Mark Satterthwaite5e8590a2019-08-14 10:44:54 -040015251 if (tid && compiler.get<SPIRType>(tid).image.dim == Dim2D)
15252 return SPVFuncImplImage2DAtomicCoords;
Hans-Kristian Arntzen1a9c9602018-02-08 13:06:29 +010015253 }
Bill Hollings4c5142b2018-06-26 17:30:21 -040015254 break;
15255 }
15256
15257 case OpImageFetch:
Chip Davis7cb817e2018-09-23 14:35:25 -050015258 case OpImageRead:
Chip Davis9fbe39c2018-09-01 01:52:23 -050015259 case OpImageWrite:
Bill Hollings4c5142b2018-06-26 17:30:21 -040015260 {
15261 // Retrieve the image type, and if it's a Buffer, emit a texel coordinate function
Chip Davis9fbe39c2018-09-01 01:52:23 -050015262 uint32_t tid = result_types[args[opcode == OpImageWrite ? 0 : 2]];
Hans-Kristian Arntzenfc4f39b2019-04-23 12:17:21 +020015263 if (tid && compiler.get<SPIRType>(tid).image.dim == DimBuffer && !compiler.msl_options.texture_buffer_native)
Bill Hollings4c5142b2018-06-26 17:30:21 -040015264 return SPVFuncImplTexelBufferCoords;
Bill Hollings1c180782017-11-05 21:34:42 -050015265 break;
15266 }
15267
Bill Hollings8f6df772017-05-19 18:14:08 -040015268 case OpExtInst:
15269 {
15270 uint32_t extension_set = args[2];
Bill Hollings1c180782017-11-05 21:34:42 -050015271 if (compiler.get<SPIRExtension>(extension_set).ext == SPIRExtension::GLSL)
Bill Hollings8f6df772017-05-19 18:14:08 -040015272 {
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +020015273 auto op_450 = static_cast<GLSLstd450>(args[3]);
Bill Hollings8f6df772017-05-19 18:14:08 -040015274 switch (op_450)
15275 {
15276 case GLSLstd450Radians:
15277 return SPVFuncImplRadians;
15278 case GLSLstd450Degrees:
15279 return SPVFuncImplDegrees;
15280 case GLSLstd450FindILsb:
15281 return SPVFuncImplFindILsb;
15282 case GLSLstd450FindSMsb:
15283 return SPVFuncImplFindSMsb;
15284 case GLSLstd450FindUMsb:
15285 return SPVFuncImplFindUMsb;
Connor McLaughlin1dd676c2018-11-07 22:24:21 +100015286 case GLSLstd450SSign:
15287 return SPVFuncImplSSign;
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +020015288 case GLSLstd450Reflect:
15289 {
15290 auto &type = compiler.get<SPIRType>(args[0]);
15291 if (type.vecsize == 1)
15292 return SPVFuncImplReflectScalar;
Chip Davis39dce882019-08-02 15:11:19 -050015293 break;
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +020015294 }
15295 case GLSLstd450Refract:
15296 {
15297 auto &type = compiler.get<SPIRType>(args[0]);
15298 if (type.vecsize == 1)
15299 return SPVFuncImplRefractScalar;
Chip Davis39dce882019-08-02 15:11:19 -050015300 break;
Hans-Kristian Arntzen041f1032019-07-03 12:24:58 +020015301 }
Hans-Kristian Arntzenc7eda1b2019-07-17 11:24:31 +020015302 case GLSLstd450FaceForward:
15303 {
15304 auto &type = compiler.get<SPIRType>(args[0]);
15305 if (type.vecsize == 1)
15306 return SPVFuncImplFaceForwardScalar;
Chip Davis39dce882019-08-02 15:11:19 -050015307 break;
Hans-Kristian Arntzenc7eda1b2019-07-17 11:24:31 +020015308 }
Bill Hollings8f6df772017-05-19 18:14:08 -040015309 case GLSLstd450MatrixInverse:
15310 {
Bill Hollings1c180782017-11-05 21:34:42 -050015311 auto &mat_type = compiler.get<SPIRType>(args[0]);
Bill Hollings8f6df772017-05-19 18:14:08 -040015312 switch (mat_type.columns)
15313 {
15314 case 2:
15315 return SPVFuncImplInverse2x2;
15316 case 3:
15317 return SPVFuncImplInverse3x3;
15318 case 4:
15319 return SPVFuncImplInverse4x4;
15320 default:
15321 break;
15322 }
15323 break;
15324 }
15325 default:
15326 break;
15327 }
15328 }
15329 break;
15330 }
15331
Chip Davis1264e272020-10-21 01:51:48 -050015332 case OpGroupNonUniformBroadcast:
15333 return SPVFuncImplSubgroupBroadcast;
15334
15335 case OpGroupNonUniformBroadcastFirst:
15336 return SPVFuncImplSubgroupBroadcastFirst;
15337
Chip Davis9d941572019-05-15 16:03:30 -050015338 case OpGroupNonUniformBallot:
15339 return SPVFuncImplSubgroupBallot;
15340
15341 case OpGroupNonUniformInverseBallot:
15342 case OpGroupNonUniformBallotBitExtract:
15343 return SPVFuncImplSubgroupBallotBitExtract;
15344
15345 case OpGroupNonUniformBallotFindLSB:
15346 return SPVFuncImplSubgroupBallotFindLSB;
15347
15348 case OpGroupNonUniformBallotFindMSB:
15349 return SPVFuncImplSubgroupBallotFindMSB;
15350
15351 case OpGroupNonUniformBallotBitCount:
15352 return SPVFuncImplSubgroupBallotBitCount;
15353
15354 case OpGroupNonUniformAllEqual:
15355 return SPVFuncImplSubgroupAllEqual;
15356
Chip Davis1264e272020-10-21 01:51:48 -050015357 case OpGroupNonUniformShuffle:
15358 return SPVFuncImplSubgroupShuffle;
15359
15360 case OpGroupNonUniformShuffleXor:
15361 return SPVFuncImplSubgroupShuffleXor;
15362
15363 case OpGroupNonUniformShuffleUp:
15364 return SPVFuncImplSubgroupShuffleUp;
15365
15366 case OpGroupNonUniformShuffleDown:
15367 return SPVFuncImplSubgroupShuffleDown;
15368
15369 case OpGroupNonUniformQuadBroadcast:
15370 return SPVFuncImplQuadBroadcast;
15371
15372 case OpGroupNonUniformQuadSwap:
15373 return SPVFuncImplQuadSwap;
15374
Bill Hollings8f6df772017-05-19 18:14:08 -040015375 default:
15376 break;
15377 }
15378 return SPVFuncImplNone;
15379}
15380
Bill Hollings32ae2ec2016-12-18 18:48:15 -050015381// Sort both type and meta member content based on builtin status (put builtins at end),
15382// then by the required sorting aspect.
Bill Hollings7d38f182016-12-21 16:31:13 -050015383void CompilerMSL::MemberSorter::sort()
Bill Hollings103aabf2016-04-06 17:42:27 -040015384{
Bill Hollingse4f0dde2017-01-31 11:02:44 -050015385 // Create a temporary array of consecutive member indices and sort it based on how
Bill Hollings32ae2ec2016-12-18 18:48:15 -050015386 // the members should be reordered, based on builtin and sorting aspect meta info.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020015387 size_t mbr_cnt = type.member_types.size();
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020015388 SmallVector<uint32_t> mbr_idxs(mbr_cnt);
Hans-Kristian Arntzen0ebb88c2020-04-30 11:48:53 +020015389 std::iota(mbr_idxs.begin(), mbr_idxs.end(), 0); // Fill with consecutive indices
Hans-Kristian Arntzena3fe9752019-12-02 12:13:15 +010015390 std::stable_sort(mbr_idxs.begin(), mbr_idxs.end(), *this); // Sort member indices based on sorting aspect
Bill Hollings103aabf2016-04-06 17:42:27 -040015391
Hans-Kristian Arntzen0ebb88c2020-04-30 11:48:53 +020015392 bool sort_is_identity = true;
15393 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
15394 {
15395 if (mbr_idx != mbr_idxs[mbr_idx])
15396 {
15397 sort_is_identity = false;
15398 break;
15399 }
15400 }
15401
15402 if (sort_is_identity)
15403 return;
15404
15405 if (meta.members.size() < type.member_types.size())
15406 {
15407 // This should never trigger in normal circumstances, but to be safe.
15408 meta.members.resize(type.member_types.size());
15409 }
15410
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020015411 // Move type and meta member info to the order defined by the sorted member indices.
15412 // This is done by creating temporary copies of both member types and meta, and then
15413 // copying back to the original content at the sorted indices.
15414 auto mbr_types_cpy = type.member_types;
15415 auto mbr_meta_cpy = meta.members;
15416 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
15417 {
15418 type.member_types[mbr_idx] = mbr_types_cpy[mbr_idxs[mbr_idx]];
15419 meta.members[mbr_idx] = mbr_meta_cpy[mbr_idxs[mbr_idx]];
15420 }
Hans-Kristian Arntzen0ebb88c2020-04-30 11:48:53 +020015421
Bill Hollings76cb8072021-10-28 10:16:34 -040015422 // If we're sorting by Offset, this might affect user code which accesses a buffer block.
15423 // We will need to redirect member indices from defined index to sorted index using reverse lookup.
Hans-Kristian Arntzen0ebb88c2020-04-30 11:48:53 +020015424 if (sort_aspect == SortAspect::Offset)
15425 {
Bill Hollings76cb8072021-10-28 10:16:34 -040015426 type.member_type_index_redirection.resize(mbr_cnt);
15427 for (uint32_t map_idx = 0; map_idx < mbr_cnt; map_idx++)
15428 type.member_type_index_redirection[mbr_idxs[map_idx]] = map_idx;
Hans-Kristian Arntzen0ebb88c2020-04-30 11:48:53 +020015429 }
Bill Hollings103aabf2016-04-06 17:42:27 -040015430}
15431
Bill Hollings7d38f182016-12-21 16:31:13 -050015432bool CompilerMSL::MemberSorter::operator()(uint32_t mbr_idx1, uint32_t mbr_idx2)
Bill Hollings103aabf2016-04-06 17:42:27 -040015433{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020015434 auto &mbr_meta1 = meta.members[mbr_idx1];
15435 auto &mbr_meta2 = meta.members[mbr_idx2];
Hans-Kristian Arntzen9a144bb2021-03-26 11:00:35 +010015436
15437 if (sort_aspect == LocationThenBuiltInType)
Hans-Kristian Arntzen0997e812021-03-25 16:48:01 +010015438 {
Hans-Kristian Arntzen9a144bb2021-03-26 11:00:35 +010015439 // Sort first by builtin status (put builtins at end), then by the sorting aspect.
15440 if (mbr_meta1.builtin != mbr_meta2.builtin)
15441 return mbr_meta2.builtin;
15442 else if (mbr_meta1.builtin)
15443 return mbr_meta1.builtin_type < mbr_meta2.builtin_type;
Hans-Kristian Arntzena64ddcd2021-05-21 12:31:33 +020015444 else if (mbr_meta1.location == mbr_meta2.location)
15445 return mbr_meta1.component < mbr_meta2.component;
Hans-Kristian Arntzen9a144bb2021-03-26 11:00:35 +010015446 else
Bill Hollingsaca1b552016-12-04 12:32:58 -050015447 return mbr_meta1.location < mbr_meta2.location;
Hans-Kristian Arntzen0997e812021-03-25 16:48:01 +010015448 }
Hans-Kristian Arntzen9a144bb2021-03-26 11:00:35 +010015449 else
15450 return mbr_meta1.offset < mbr_meta2.offset;
Bill Hollings103aabf2016-04-06 17:42:27 -040015451}
Bill Hollings484931d2017-02-28 21:44:36 -050015452
15453CompilerMSL::MemberSorter::MemberSorter(SPIRType &t, Meta &m, SortAspect sa)
15454 : type(t)
15455 , meta(m)
15456 , sort_aspect(sa)
15457{
15458 // Ensure enough meta info is available
15459 meta.members.resize(max(type.member_types.size(), meta.members.size()));
15460}
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +020015461
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +020015462void CompilerMSL::remap_constexpr_sampler(VariableID id, const MSLConstexprSampler &sampler)
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +020015463{
15464 auto &type = get<SPIRType>(get<SPIRVariable>(id).basetype);
15465 if (type.basetype != SPIRType::SampledImage && type.basetype != SPIRType::Sampler)
15466 SPIRV_CROSS_THROW("Can only remap SampledImage and Sampler type.");
Hans-Kristian Arntzen64f94612018-04-17 17:47:15 +020015467 if (!type.array.empty())
15468 SPIRV_CROSS_THROW("Can not remap array of samplers.");
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020015469 constexpr_samplers_by_id[id] = sampler;
15470}
15471
Hans-Kristian Arntzenb4e01632019-06-21 16:02:22 +020015472void CompilerMSL::remap_constexpr_sampler_by_binding(uint32_t desc_set, uint32_t binding,
15473 const MSLConstexprSampler &sampler)
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020015474{
15475 constexpr_samplers_by_binding[{ desc_set, binding }] = sampler;
Hans-Kristian Arntzendf58deb2018-04-17 17:43:10 +020015476}
Hans-Kristian Arntzend94d20f2018-06-22 11:30:13 +020015477
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020015478void CompilerMSL::cast_from_variable_load(uint32_t source_id, std::string &expr, const SPIRType &expr_type)
Hans-Kristian Arntzend94d20f2018-06-22 11:30:13 +020015479{
Chip Davis6757ef82018-09-11 11:15:17 -050015480 auto *var = maybe_get_backing_variable(source_id);
15481 if (var)
15482 source_id = var->self;
15483
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020015484 // Type fixups for workgroup variables if they are booleans.
15485 if (var && var->storage == StorageClassWorkgroup && expr_type.basetype == SPIRType::Boolean)
15486 expr = join(type_to_glsl(expr_type), "(", expr, ")");
15487
Chip Davis6757ef82018-09-11 11:15:17 -050015488 // Only interested in standalone builtin variables.
15489 if (!has_decoration(source_id, DecorationBuiltIn))
15490 return;
15491
15492 auto builtin = static_cast<BuiltIn>(get_decoration(source_id, DecorationBuiltIn));
15493 auto expected_type = expr_type.basetype;
Chip Davis3e6010d2020-10-14 15:04:03 -050015494 auto expected_width = expr_type.width;
Chip Davis6757ef82018-09-11 11:15:17 -050015495 switch (builtin)
15496 {
15497 case BuiltInGlobalInvocationId:
15498 case BuiltInLocalInvocationId:
15499 case BuiltInWorkgroupId:
15500 case BuiltInLocalInvocationIndex:
15501 case BuiltInWorkgroupSize:
15502 case BuiltInNumWorkgroups:
Chip Davisec857f62018-09-19 09:13:30 -050015503 case BuiltInLayer:
15504 case BuiltInViewportIndex:
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020015505 case BuiltInFragStencilRefEXT:
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020015506 case BuiltInPrimitiveId:
Hans-Kristian Arntzenab3798f2019-06-24 12:31:54 +020015507 case BuiltInSubgroupSize:
15508 case BuiltInSubgroupLocalInvocationId:
Chip Davis7eecf5a2019-05-31 12:06:20 -050015509 case BuiltInViewIndex:
Hans-Kristian Arntzen07c76f62019-08-29 13:56:37 +020015510 case BuiltInVertexIndex:
15511 case BuiltInInstanceIndex:
15512 case BuiltInBaseInstance:
15513 case BuiltInBaseVertex:
Chip Davis6757ef82018-09-11 11:15:17 -050015514 expected_type = SPIRType::UInt;
Chip Davis3e6010d2020-10-14 15:04:03 -050015515 expected_width = 32;
Chip Davis6757ef82018-09-11 11:15:17 -050015516 break;
15517
Chip Daviseb89c3a2019-02-03 23:58:46 -060015518 case BuiltInTessLevelInner:
15519 case BuiltInTessLevelOuter:
Chip Davisf3c09422019-02-22 12:11:17 -060015520 if (get_execution_model() == ExecutionModelTessellationControl)
Chip Davis3e6010d2020-10-14 15:04:03 -050015521 {
Chip Davisf3c09422019-02-22 12:11:17 -060015522 expected_type = SPIRType::Half;
Chip Davis3e6010d2020-10-14 15:04:03 -050015523 expected_width = 16;
15524 }
Chip Daviseb89c3a2019-02-03 23:58:46 -060015525 break;
15526
Chip Davis6757ef82018-09-11 11:15:17 -050015527 default:
15528 break;
15529 }
15530
15531 if (expected_type != expr_type.basetype)
Chip Davis3e6010d2020-10-14 15:04:03 -050015532 {
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +010015533 if (!expr_type.array.empty() && (builtin == BuiltInTessLevelInner || builtin == BuiltInTessLevelOuter))
Chip Davis3e6010d2020-10-14 15:04:03 -050015534 {
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +010015535 // Triggers when loading TessLevel directly as an array.
15536 // Need explicit padding + cast.
15537 auto wrap_expr = join(type_to_glsl(expr_type), "({ ");
15538
15539 uint32_t array_size = get_physical_tess_level_array_size(builtin);
15540 for (uint32_t i = 0; i < array_size; i++)
15541 {
15542 if (array_size > 1)
15543 wrap_expr += join("float(", expr, "[", i, "])");
15544 else
15545 wrap_expr += join("float(", expr, ")");
15546 if (i + 1 < array_size)
15547 wrap_expr += ", ";
15548 }
15549
15550 if (get_execution_mode_bitset().get(ExecutionModeTriangles))
15551 wrap_expr += ", 0.0";
15552
15553 wrap_expr += " })";
15554 expr = std::move(wrap_expr);
Chip Davis3e6010d2020-10-14 15:04:03 -050015555 }
15556 else
15557 {
Hans-Kristian Arntzen85704f72021-02-17 13:18:47 +010015558 // These are of different widths, so we cannot do a straight bitcast.
15559 if (expected_width != expr_type.width)
15560 expr = join(type_to_glsl(expr_type), "(", expr, ")");
15561 else
15562 expr = bitcast_expression(expr_type, expected_type, expr);
Chip Davis3e6010d2020-10-14 15:04:03 -050015563 }
15564 }
Hans-Kristian Arntzend94d20f2018-06-22 11:30:13 +020015565}
15566
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020015567void CompilerMSL::cast_to_variable_store(uint32_t target_id, std::string &expr, const SPIRType &expr_type)
Hans-Kristian Arntzend94d20f2018-06-22 11:30:13 +020015568{
Chip Daviseb89c3a2019-02-03 23:58:46 -060015569 auto *var = maybe_get_backing_variable(target_id);
15570 if (var)
15571 target_id = var->self;
15572
Hans-Kristian Arntzenedf247f2021-10-25 10:55:11 +020015573 // Type fixups for workgroup variables if they are booleans.
15574 if (var && var->storage == StorageClassWorkgroup && expr_type.basetype == SPIRType::Boolean)
15575 {
15576 auto short_type = expr_type;
15577 short_type.basetype = SPIRType::Short;
15578 expr = join(type_to_glsl(short_type), "(", expr, ")");
15579 }
15580
Chip Davisec857f62018-09-19 09:13:30 -050015581 // Only interested in standalone builtin variables.
15582 if (!has_decoration(target_id, DecorationBuiltIn))
15583 return;
15584
15585 auto builtin = static_cast<BuiltIn>(get_decoration(target_id, DecorationBuiltIn));
15586 auto expected_type = expr_type.basetype;
Chip Davis3e6010d2020-10-14 15:04:03 -050015587 auto expected_width = expr_type.width;
Chip Davisec857f62018-09-19 09:13:30 -050015588 switch (builtin)
15589 {
15590 case BuiltInLayer:
15591 case BuiltInViewportIndex:
Hans-Kristian Arntzen14d0a1e2019-06-12 10:06:59 +020015592 case BuiltInFragStencilRefEXT:
Hans-Kristian Arntzen2e1cee52019-06-13 11:33:40 +020015593 case BuiltInPrimitiveId:
Chip Davis7eecf5a2019-05-31 12:06:20 -050015594 case BuiltInViewIndex:
Chip Davisec857f62018-09-19 09:13:30 -050015595 expected_type = SPIRType::UInt;
Chip Davis3e6010d2020-10-14 15:04:03 -050015596 expected_width = 32;
Chip Davisec857f62018-09-19 09:13:30 -050015597 break;
15598
Chip Daviseb89c3a2019-02-03 23:58:46 -060015599 case BuiltInTessLevelInner:
15600 case BuiltInTessLevelOuter:
15601 expected_type = SPIRType::Half;
Chip Davis3e6010d2020-10-14 15:04:03 -050015602 expected_width = 16;
Chip Daviseb89c3a2019-02-03 23:58:46 -060015603 break;
15604
Chip Davisec857f62018-09-19 09:13:30 -050015605 default:
15606 break;
15607 }
15608
15609 if (expected_type != expr_type.basetype)
15610 {
Chip Davis3e6010d2020-10-14 15:04:03 -050015611 if (expected_width != expr_type.width)
Chip Daviseb89c3a2019-02-03 23:58:46 -060015612 {
15613 // These are of different widths, so we cannot do a straight bitcast.
Chip Davis3e6010d2020-10-14 15:04:03 -050015614 auto type = expr_type;
15615 type.basetype = expected_type;
15616 type.width = expected_width;
15617 expr = join(type_to_glsl(type), "(", expr, ")");
Chip Daviseb89c3a2019-02-03 23:58:46 -060015618 }
15619 else
15620 {
15621 auto type = expr_type;
15622 type.basetype = expected_type;
15623 expr = bitcast_expression(type, expr_type.basetype, expr);
15624 }
Chip Davisec857f62018-09-19 09:13:30 -050015625 }
Hans-Kristian Arntzend94d20f2018-06-22 11:30:13 +020015626}
Hans-Kristian Arntzen2bf57d62018-07-05 15:29:49 +020015627
Hans-Kristian Arntzenb8905bb2020-03-26 11:21:23 +010015628string CompilerMSL::to_initializer_expression(const SPIRVariable &var)
Hans-Kristian Arntzen2bf57d62018-07-05 15:29:49 +020015629{
15630 // We risk getting an array initializer here with MSL. If we have an array.
15631 // FIXME: We cannot handle non-constant arrays being initialized.
15632 // We will need to inject spvArrayCopy here somehow ...
15633 auto &type = get<SPIRType>(var.basetype);
Chip Davis688c5fc2020-02-20 21:38:28 -060015634 string expr;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020015635 if (ir.ids[var.initializer].get_type() == TypeConstant &&
15636 (!type.array.empty() || type.basetype == SPIRType::Struct))
Chip Davis688c5fc2020-02-20 21:38:28 -060015637 expr = constant_expression(get<SPIRConstant>(var.initializer));
Hans-Kristian Arntzen2bf57d62018-07-05 15:29:49 +020015638 else
Chip Davis688c5fc2020-02-20 21:38:28 -060015639 expr = CompilerGLSL::to_initializer_expression(var);
15640 // If the initializer has more vector components than the variable, add a swizzle.
15641 // FIXME: This can't handle arrays or structs.
15642 auto &init_type = expression_type(var.initializer);
15643 if (type.array.empty() && type.basetype != SPIRType::Struct && init_type.vecsize > type.vecsize)
15644 expr = enclose_expression(expr + vector_swizzle(type.vecsize, 0));
15645 return expr;
Hans-Kristian Arntzen2bf57d62018-07-05 15:29:49 +020015646}
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015647
Hans-Kristian Arntzenb8905bb2020-03-26 11:21:23 +010015648string CompilerMSL::to_zero_initialized_expression(uint32_t)
15649{
15650 return "{}";
15651}
15652
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010015653bool CompilerMSL::descriptor_set_is_argument_buffer(uint32_t desc_set) const
15654{
15655 if (!msl_options.argument_buffers)
15656 return false;
15657 if (desc_set >= kMaxArgumentBuffers)
15658 return false;
15659
Hans-Kristian Arntzene2aadf82019-03-15 21:53:21 +010015660 return (argument_buffer_discrete_mask & (1u << desc_set)) == 0;
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010015661}
15662
Hans-Kristian Arntzen893a0112021-01-07 15:00:45 +010015663bool CompilerMSL::is_supported_argument_buffer_type(const SPIRType &type) const
15664{
15665 // Very specifically, image load-store in argument buffers are disallowed on MSL on iOS.
15666 // But we won't know when the argument buffer is encoded whether this image will have
15667 // a NonWritable decoration. So just use discrete arguments for all storage images
15668 // on iOS.
15669 bool is_storage_image = type.basetype == SPIRType::Image && type.image.sampled == 2;
15670 bool is_supported_type = !msl_options.is_ios() || !is_storage_image;
15671 return !type_is_msl_framebuffer_fetch(type) && is_supported_type;
15672}
15673
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015674void CompilerMSL::analyze_argument_buffers()
15675{
15676 // Gather all used resources and sort them out into argument buffers.
15677 // Each argument buffer corresponds to a descriptor set in SPIR-V.
15678 // The [[id(N)]] values used correspond to the resource mapping we have for MSL.
15679 // Otherwise, the binding number is used, but this is generally not safe some types like
15680 // combined image samplers and arrays of resources. Metal needs different indices here,
15681 // while SPIR-V can have one descriptor set binding. To use argument buffers in practice,
15682 // you will need to use the remapping from the API.
15683 for (auto &id : argument_buffer_ids)
15684 id = 0;
15685
15686 // Output resources, sorted by resource index & type.
15687 struct Resource
15688 {
15689 SPIRVariable *var;
15690 string name;
15691 SPIRType::BaseType basetype;
15692 uint32_t index;
Chip Davis39dce882019-08-02 15:11:19 -050015693 uint32_t plane;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015694 };
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020015695 SmallVector<Resource> resources_in_set[kMaxArgumentBuffers];
Chip Davisae6c05f2020-01-25 13:40:51 -060015696 SmallVector<uint32_t> inline_block_vars;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015697
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015698 bool set_needs_swizzle_buffer[kMaxArgumentBuffers] = {};
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015699 bool set_needs_buffer_sizes[kMaxArgumentBuffers] = {};
15700 bool needs_buffer_sizes = false;
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015701
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015702 ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, SPIRVariable &var) {
15703 if ((var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
15704 var.storage == StorageClassStorageBuffer) &&
15705 !is_hidden_variable(var))
15706 {
15707 uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010015708 // Ignore if it's part of a push descriptor set.
15709 if (!descriptor_set_is_argument_buffer(desc_set))
15710 return;
15711
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015712 uint32_t var_id = var.self;
15713 auto &type = get_variable_data_type(var);
15714
15715 if (desc_set >= kMaxArgumentBuffers)
15716 SPIRV_CROSS_THROW("Descriptor set index is out of range.");
15717
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020015718 const MSLConstexprSampler *constexpr_sampler = nullptr;
15719 if (type.basetype == SPIRType::SampledImage || type.basetype == SPIRType::Sampler)
15720 {
15721 constexpr_sampler = find_constexpr_sampler(var_id);
15722 if (constexpr_sampler)
15723 {
15724 // Mark this ID as a constexpr sampler for later in case it came from set/bindings.
15725 constexpr_samplers_by_id[var_id] = *constexpr_sampler;
15726 }
15727 }
15728
Chip Davisae6c05f2020-01-25 13:40:51 -060015729 uint32_t binding = get_decoration(var_id, DecorationBinding);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015730 if (type.basetype == SPIRType::SampledImage)
15731 {
15732 add_resource_name(var_id);
15733
Chip Davis39dce882019-08-02 15:11:19 -050015734 uint32_t plane_count = 1;
15735 if (constexpr_sampler && constexpr_sampler->ycbcr_conversion_enable)
15736 plane_count = constexpr_sampler->planes;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015737
Chip Davis39dce882019-08-02 15:11:19 -050015738 for (uint32_t i = 0; i < plane_count; i++)
15739 {
15740 uint32_t image_resource_index = get_metal_resource_index(var, SPIRType::Image, i);
15741 resources_in_set[desc_set].push_back(
15742 { &var, to_name(var_id), SPIRType::Image, image_resource_index, i });
15743 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015744
Hans-Kristian Arntzen30bb1972019-06-10 15:41:36 +020015745 if (type.image.dim != DimBuffer && !constexpr_sampler)
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015746 {
Chip Davis39dce882019-08-02 15:11:19 -050015747 uint32_t sampler_resource_index = get_metal_resource_index(var, SPIRType::Sampler);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015748 resources_in_set[desc_set].push_back(
Chip Davis39dce882019-08-02 15:11:19 -050015749 { &var, to_sampler_expression(var_id), SPIRType::Sampler, sampler_resource_index, 0 });
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015750 }
15751 }
Chip Davisae6c05f2020-01-25 13:40:51 -060015752 else if (inline_uniform_blocks.count(SetBindingPair{ desc_set, binding }))
15753 {
15754 inline_block_vars.push_back(var_id);
15755 }
Hans-Kristian Arntzen893a0112021-01-07 15:00:45 +010015756 else if (!constexpr_sampler && is_supported_argument_buffer_type(type))
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015757 {
15758 // constexpr samplers are not declared as resources.
Chip Davisae6c05f2020-01-25 13:40:51 -060015759 // Inline uniform blocks are always emitted at the end.
Hans-Kristian Arntzen893a0112021-01-07 15:00:45 +010015760 add_resource_name(var_id);
15761 resources_in_set[desc_set].push_back(
15762 { &var, to_name(var_id), type.basetype, get_metal_resource_index(var, type.basetype), 0 });
Chip Davis9cafea62020-10-13 02:33:06 -050015763
Hans-Kristian Arntzen893a0112021-01-07 15:00:45 +010015764 // Emulate texture2D atomic operations
15765 if (atomic_image_vars.count(var.self))
15766 {
15767 uint32_t buffer_resource_index = get_metal_resource_index(var, SPIRType::AtomicCounter, 0);
15768 resources_in_set[desc_set].push_back(
15769 { &var, to_name(var_id) + "_atomic", SPIRType::Struct, buffer_resource_index, 0 });
Chip Davis10381702019-09-04 13:57:17 -050015770 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015771 }
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015772
15773 // Check if this descriptor set needs a swizzle buffer.
15774 if (needs_swizzle_buffer_def && is_sampled_image_type(type))
15775 set_needs_swizzle_buffer[desc_set] = true;
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015776 else if (buffers_requiring_array_length.count(var_id) != 0)
15777 {
15778 set_needs_buffer_sizes[desc_set] = true;
15779 needs_buffer_sizes = true;
15780 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015781 }
15782 });
15783
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015784 if (needs_swizzle_buffer_def || needs_buffer_sizes)
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015785 {
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015786 uint32_t uint_ptr_type_id = 0;
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015787
15788 // We might have to add a swizzle buffer resource to the set.
15789 for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
15790 {
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015791 if (!set_needs_swizzle_buffer[desc_set] && !set_needs_buffer_sizes[desc_set])
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015792 continue;
15793
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015794 if (uint_ptr_type_id == 0)
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015795 {
Chip Davis884bc6d2020-07-22 15:25:10 -060015796 uint_ptr_type_id = ir.increase_bound_by(1);
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015797
15798 // Create a buffer to hold extra data, including the swizzle constants.
Chip Davis884bc6d2020-07-22 15:25:10 -060015799 SPIRType uint_type_pointer = get_uint_type();
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015800 uint_type_pointer.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010015801 uint_type_pointer.pointer_depth++;
Chip Davis884bc6d2020-07-22 15:25:10 -060015802 uint_type_pointer.parent_type = get_uint_type_id();
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015803 uint_type_pointer.storage = StorageClassUniform;
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015804 set<SPIRType>(uint_ptr_type_id, uint_type_pointer);
15805 set_decoration(uint_ptr_type_id, DecorationArrayStride, 4);
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015806 }
15807
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015808 if (set_needs_swizzle_buffer[desc_set])
15809 {
15810 uint32_t var_id = ir.increase_bound_by(1);
15811 auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
15812 set_name(var_id, "spvSwizzleConstants");
15813 set_decoration(var_id, DecorationDescriptorSet, desc_set);
15814 set_decoration(var_id, DecorationBinding, kSwizzleBufferBinding);
15815 resources_in_set[desc_set].push_back(
Chip Davis39dce882019-08-02 15:11:19 -050015816 { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 0 });
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015817 }
15818
15819 if (set_needs_buffer_sizes[desc_set])
15820 {
15821 uint32_t var_id = ir.increase_bound_by(1);
15822 auto &var = set<SPIRVariable>(var_id, uint_ptr_type_id, StorageClassUniformConstant);
15823 set_name(var_id, "spvBufferSizeConstants");
15824 set_decoration(var_id, DecorationDescriptorSet, desc_set);
15825 set_decoration(var_id, DecorationBinding, kBufferSizeBufferBinding);
15826 resources_in_set[desc_set].push_back(
Chip Davis39dce882019-08-02 15:11:19 -050015827 { &var, to_name(var_id), SPIRType::UInt, get_metal_resource_index(var, SPIRType::UInt), 0 });
Hans-Kristian Arntzen7b9e0fb2019-05-27 11:59:29 +020015828 }
Hans-Kristian Arntzeneaf7afe2019-05-09 12:15:45 +020015829 }
15830 }
15831
Chip Davisae6c05f2020-01-25 13:40:51 -060015832 // Now add inline uniform blocks.
15833 for (uint32_t var_id : inline_block_vars)
15834 {
15835 auto &var = get<SPIRVariable>(var_id);
15836 uint32_t desc_set = get_decoration(var_id, DecorationDescriptorSet);
15837 add_resource_name(var_id);
15838 resources_in_set[desc_set].push_back(
15839 { &var, to_name(var_id), SPIRType::Struct, get_metal_resource_index(var, SPIRType::Struct), 0 });
15840 }
15841
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015842 for (uint32_t desc_set = 0; desc_set < kMaxArgumentBuffers; desc_set++)
15843 {
15844 auto &resources = resources_in_set[desc_set];
15845 if (resources.empty())
15846 continue;
15847
Hans-Kristian Arntzenb3380ec2019-03-15 14:07:03 +010015848 assert(descriptor_set_is_argument_buffer(desc_set));
15849
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015850 uint32_t next_id = ir.increase_bound_by(3);
15851 uint32_t type_id = next_id + 1;
15852 uint32_t ptr_type_id = next_id + 2;
15853 argument_buffer_ids[desc_set] = next_id;
15854
15855 auto &buffer_type = set<SPIRType>(type_id);
Hans-Kristian Arntzen4bb673a2019-10-14 12:51:48 +020015856
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015857 buffer_type.basetype = SPIRType::Struct;
Hans-Kristian Arntzen4bb673a2019-10-14 12:51:48 +020015858
15859 if ((argument_buffer_device_storage_mask & (1u << desc_set)) != 0)
15860 {
15861 buffer_type.storage = StorageClassStorageBuffer;
15862 // Make sure the argument buffer gets marked as const device.
15863 set_decoration(next_id, DecorationNonWritable);
15864 // Need to mark the type as a Block to enable this.
15865 set_decoration(type_id, DecorationBlock);
15866 }
15867 else
15868 buffer_type.storage = StorageClassUniform;
15869
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015870 set_name(type_id, join("spvDescriptorSetBuffer", desc_set));
15871
15872 auto &ptr_type = set<SPIRType>(ptr_type_id);
15873 ptr_type = buffer_type;
15874 ptr_type.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010015875 ptr_type.pointer_depth++;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015876 ptr_type.parent_type = type_id;
15877
15878 uint32_t buffer_variable_id = next_id;
15879 set<SPIRVariable>(buffer_variable_id, ptr_type_id, StorageClassUniform);
15880 set_name(buffer_variable_id, join("spvDescriptorSet", desc_set));
15881
15882 // Ids must be emitted in ID order.
15883 sort(begin(resources), end(resources), [&](const Resource &lhs, const Resource &rhs) -> bool {
15884 return tie(lhs.index, lhs.basetype) < tie(rhs.index, rhs.basetype);
15885 });
15886
15887 uint32_t member_index = 0;
Bill Hollings17dab612021-04-13 19:01:20 -040015888 uint32_t next_arg_buff_index = 0;
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015889 for (auto &resource : resources)
15890 {
15891 auto &var = *resource.var;
15892 auto &type = get_variable_data_type(var);
Bill Hollings17dab612021-04-13 19:01:20 -040015893
15894 // If needed, synthesize and add padding members.
15895 // member_index and next_arg_buff_index are incremented when padding members are added.
15896 if (msl_options.pad_argument_buffer_resources)
15897 {
15898 while (resource.index > next_arg_buff_index)
15899 {
Bill Hollings9866cf42021-04-16 09:05:15 -040015900 auto &rez_bind = get_argument_buffer_resource(desc_set, next_arg_buff_index);
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015901 switch (rez_bind.basetype)
Bill Hollings17dab612021-04-13 19:01:20 -040015902 {
Bill Hollings9866cf42021-04-16 09:05:15 -040015903 case SPIRType::Void:
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015904 case SPIRType::Boolean:
15905 case SPIRType::SByte:
15906 case SPIRType::UByte:
15907 case SPIRType::Short:
15908 case SPIRType::UShort:
15909 case SPIRType::Int:
15910 case SPIRType::UInt:
15911 case SPIRType::Int64:
15912 case SPIRType::UInt64:
15913 case SPIRType::AtomicCounter:
15914 case SPIRType::Half:
15915 case SPIRType::Float:
15916 case SPIRType::Double:
15917 add_argument_buffer_padding_buffer_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
Bill Hollings9866cf42021-04-16 09:05:15 -040015918 break;
15919 case SPIRType::Image:
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015920 add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
Bill Hollings9866cf42021-04-16 09:05:15 -040015921 break;
15922 case SPIRType::Sampler:
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015923 add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
Bill Hollings9866cf42021-04-16 09:05:15 -040015924 break;
15925 case SPIRType::SampledImage:
Bill Hollings9060e5a2021-04-16 15:00:59 -040015926 if (next_arg_buff_index == rez_bind.msl_sampler)
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015927 add_argument_buffer_padding_sampler_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
Bill Hollings9060e5a2021-04-16 15:00:59 -040015928 else
Bill Hollingsb3bfe222021-04-18 17:34:55 -040015929 add_argument_buffer_padding_image_type(buffer_type, member_index, next_arg_buff_index, rez_bind);
Bill Hollings9866cf42021-04-16 09:05:15 -040015930 break;
15931 default:
Bill Hollings9866cf42021-04-16 09:05:15 -040015932 break;
Bill Hollings17dab612021-04-13 19:01:20 -040015933 }
Bill Hollings17dab612021-04-13 19:01:20 -040015934 }
15935
15936 // Adjust the number of slots consumed by current member itself.
15937 // If actual member is an array, allow runtime array resolution as well.
15938 uint32_t elem_cnt = type.array.empty() ? 1 : to_array_size_literal(type);
15939 if (elem_cnt == 0)
15940 elem_cnt = get_resource_array_size(var.self);
15941
15942 next_arg_buff_index += elem_cnt;
15943 }
15944
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015945 string mbr_name = ensure_valid_name(resource.name, "m");
Chip Davis39dce882019-08-02 15:11:19 -050015946 if (resource.plane > 0)
15947 mbr_name += join(plane_name_suffix, resource.plane);
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015948 set_member_name(buffer_type.self, member_index, mbr_name);
15949
15950 if (resource.basetype == SPIRType::Sampler && type.basetype != SPIRType::Sampler)
15951 {
15952 // Have to synthesize a sampler type here.
15953
15954 bool type_is_array = !type.array.empty();
15955 uint32_t sampler_type_id = ir.increase_bound_by(type_is_array ? 2 : 1);
15956 auto &new_sampler_type = set<SPIRType>(sampler_type_id);
15957 new_sampler_type.basetype = SPIRType::Sampler;
15958 new_sampler_type.storage = StorageClassUniformConstant;
15959
15960 if (type_is_array)
15961 {
15962 uint32_t sampler_type_array_id = sampler_type_id + 1;
15963 auto &sampler_type_array = set<SPIRType>(sampler_type_array_id);
15964 sampler_type_array = new_sampler_type;
15965 sampler_type_array.array = type.array;
15966 sampler_type_array.array_size_literal = type.array_size_literal;
15967 sampler_type_array.parent_type = sampler_type_id;
15968 buffer_type.member_types.push_back(sampler_type_array_id);
15969 }
15970 else
15971 buffer_type.member_types.push_back(sampler_type_id);
15972 }
15973 else
15974 {
Chip Daviscb359342019-09-05 23:14:12 -050015975 uint32_t binding = get_decoration(var.self, DecorationBinding);
15976 SetBindingPair pair = { desc_set, binding };
15977
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015978 if (resource.basetype == SPIRType::Image || resource.basetype == SPIRType::Sampler ||
15979 resource.basetype == SPIRType::SampledImage)
15980 {
15981 // Drop pointer information when we emit the resources into a struct.
15982 buffer_type.member_types.push_back(get_variable_data_type_id(var));
Chip Davis39dce882019-08-02 15:11:19 -050015983 if (resource.plane == 0)
15984 set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010015985 }
Chip Daviscb359342019-09-05 23:14:12 -050015986 else if (buffers_requiring_dynamic_offset.count(pair))
15987 {
15988 // Don't set the qualified name here; we'll define a variable holding the corrected buffer address later.
15989 buffer_type.member_types.push_back(var.basetype);
15990 buffers_requiring_dynamic_offset[pair].second = var.self;
15991 }
Chip Davisfedbc352019-12-16 22:58:16 -060015992 else if (inline_uniform_blocks.count(pair))
15993 {
15994 // Put the buffer block itself into the argument buffer.
15995 buffer_type.member_types.push_back(get_variable_data_type_id(var));
15996 set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
15997 }
Chip Davis9cafea62020-10-13 02:33:06 -050015998 else if (atomic_image_vars.count(var.self))
15999 {
16000 // Emulate texture2D atomic operations.
16001 // Don't set the qualified name: it's already set for this variable,
16002 // and the code that references the buffer manually appends "_atomic"
16003 // to the name.
16004 uint32_t offset = ir.increase_bound_by(2);
16005 uint32_t atomic_type_id = offset;
16006 uint32_t type_ptr_id = offset + 1;
16007
16008 SPIRType atomic_type;
16009 atomic_type.basetype = SPIRType::AtomicCounter;
16010 atomic_type.width = 32;
16011 atomic_type.vecsize = 1;
16012 set<SPIRType>(atomic_type_id, atomic_type);
16013
16014 atomic_type.pointer = true;
Hans-Kristian Arntzen97796e02021-02-26 12:50:24 +010016015 atomic_type.pointer_depth++;
Chip Davis9cafea62020-10-13 02:33:06 -050016016 atomic_type.parent_type = atomic_type_id;
16017 atomic_type.storage = StorageClassStorageBuffer;
16018 auto &atomic_ptr_type = set<SPIRType>(type_ptr_id, atomic_type);
16019 atomic_ptr_type.self = atomic_type_id;
16020
16021 buffer_type.member_types.push_back(type_ptr_id);
16022 }
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010016023 else
16024 {
16025 // Resources will be declared as pointers not references, so automatically dereference as appropriate.
16026 buffer_type.member_types.push_back(var.basetype);
16027 if (type.array.empty())
16028 set_qualified_name(var.self, join("(*", to_name(buffer_variable_id), ".", mbr_name, ")"));
16029 else
16030 set_qualified_name(var.self, join(to_name(buffer_variable_id), ".", mbr_name));
16031 }
16032 }
16033
Hans-Kristian Arntzene2c95bd2019-06-21 12:44:33 +020016034 set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationResourceIndexPrimary,
Hans-Kristian Arntzene47a77d2019-03-14 10:29:34 +010016035 resource.index);
16036 set_extended_member_decoration(buffer_type.self, member_index, SPIRVCrossDecorationInterfaceOrigID,
16037 var.self);
16038 member_index++;
16039 }
16040 }
16041}
Hans-Kristian Arntzenc3bd1362020-01-16 11:07:30 +010016042
Bill Hollings17dab612021-04-13 19:01:20 -040016043// Return the resource type of the app-provided resources for the descriptor set,
16044// that matches the resource index of the argument buffer index.
Bill Hollings9866cf42021-04-16 09:05:15 -040016045// This is a two-step lookup, first lookup the resource binding number from the argument buffer index,
16046// then lookup the resource binding using the binding number.
16047MSLResourceBinding &CompilerMSL::get_argument_buffer_resource(uint32_t desc_set, uint32_t arg_idx)
Bill Hollings17dab612021-04-13 19:01:20 -040016048{
Bill Hollings9866cf42021-04-16 09:05:15 -040016049 auto stage = get_entry_point().model;
16050 StageSetBinding arg_idx_tuple = { stage, desc_set, arg_idx };
16051 auto arg_itr = resource_arg_buff_idx_to_binding_number.find(arg_idx_tuple);
16052 if (arg_itr != end(resource_arg_buff_idx_to_binding_number))
Bill Hollings17dab612021-04-13 19:01:20 -040016053 {
Bill Hollings9866cf42021-04-16 09:05:15 -040016054 StageSetBinding bind_tuple = { stage, desc_set, arg_itr->second };
16055 auto bind_itr = resource_bindings.find(bind_tuple);
16056 if (bind_itr != end(resource_bindings))
16057 return bind_itr->second.first;
Bill Hollings17dab612021-04-13 19:01:20 -040016058 }
Bill Hollings9866cf42021-04-16 09:05:15 -040016059 SPIRV_CROSS_THROW("Argument buffer resource base type could not be determined. When padding argument buffer "
16060 "elements, all descriptor set resources must be supplied with a base type by the app.");
Bill Hollings17dab612021-04-13 19:01:20 -040016061}
16062
16063// Adds an argument buffer padding argument buffer type as one or more members of the struct type at the member index.
16064// Metal does not support arrays of buffers, so these are emitted as multiple struct members.
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016065void CompilerMSL::add_argument_buffer_padding_buffer_type(SPIRType &struct_type, uint32_t &mbr_idx,
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016066 uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
Bill Hollings17dab612021-04-13 19:01:20 -040016067{
16068 if (!argument_buffer_padding_buffer_type_id)
16069 {
16070 uint32_t buff_type_id = ir.increase_bound_by(2);
16071 auto &buff_type = set<SPIRType>(buff_type_id);
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016072 buff_type.basetype = rez_bind.basetype;
Bill Hollings17dab612021-04-13 19:01:20 -040016073 buff_type.storage = StorageClassUniformConstant;
16074
16075 uint32_t ptr_type_id = buff_type_id + 1;
16076 auto &ptr_type = set<SPIRType>(ptr_type_id);
16077 ptr_type = buff_type;
16078 ptr_type.pointer = true;
16079 ptr_type.pointer_depth++;
16080 ptr_type.parent_type = buff_type_id;
16081
16082 argument_buffer_padding_buffer_type_id = ptr_type_id;
16083 }
Bill Hollings9866cf42021-04-16 09:05:15 -040016084
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016085 for (uint32_t rez_idx = 0; rez_idx < rez_bind.count; rez_idx++)
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016086 add_argument_buffer_padding_type(argument_buffer_padding_buffer_type_id, struct_type, mbr_idx, arg_buff_index, 1);
Bill Hollings17dab612021-04-13 19:01:20 -040016087}
16088
16089// Adds an argument buffer padding argument image type as a member of the struct type at the member index.
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016090void CompilerMSL::add_argument_buffer_padding_image_type(SPIRType &struct_type, uint32_t &mbr_idx,
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016091 uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
Bill Hollings17dab612021-04-13 19:01:20 -040016092{
16093 if (!argument_buffer_padding_image_type_id)
16094 {
16095 uint32_t base_type_id = ir.increase_bound_by(2);
16096 auto &base_type = set<SPIRType>(base_type_id);
16097 base_type.basetype = SPIRType::Float;
16098 base_type.width = 32;
16099
16100 uint32_t img_type_id = base_type_id + 1;
16101 auto &img_type = set<SPIRType>(img_type_id);
16102 img_type.basetype = SPIRType::Image;
16103 img_type.storage = StorageClassUniformConstant;
16104
16105 img_type.image.type = base_type_id;
16106 img_type.image.dim = Dim2D;
16107 img_type.image.depth = false;
16108 img_type.image.arrayed = false;
16109 img_type.image.ms = false;
16110 img_type.image.sampled = 1;
16111 img_type.image.format = ImageFormatUnknown;
16112 img_type.image.access = AccessQualifierMax;
16113
16114 argument_buffer_padding_image_type_id = img_type_id;
16115 }
16116
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016117 add_argument_buffer_padding_type(argument_buffer_padding_image_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
Bill Hollings17dab612021-04-13 19:01:20 -040016118}
16119
16120// Adds an argument buffer padding argument sampler type as a member of the struct type at the member index.
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016121void CompilerMSL::add_argument_buffer_padding_sampler_type(SPIRType &struct_type, uint32_t &mbr_idx,
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016122 uint32_t &arg_buff_index, MSLResourceBinding &rez_bind)
Bill Hollings17dab612021-04-13 19:01:20 -040016123{
16124 if (!argument_buffer_padding_sampler_type_id)
16125 {
16126 uint32_t samp_type_id = ir.increase_bound_by(1);
16127 auto &samp_type = set<SPIRType>(samp_type_id);
16128 samp_type.basetype = SPIRType::Sampler;
16129 samp_type.storage = StorageClassUniformConstant;
16130
16131 argument_buffer_padding_sampler_type_id = samp_type_id;
16132 }
16133
Bill Hollingsb3bfe222021-04-18 17:34:55 -040016134 add_argument_buffer_padding_type(argument_buffer_padding_sampler_type_id, struct_type, mbr_idx, arg_buff_index, rez_bind.count);
Bill Hollings17dab612021-04-13 19:01:20 -040016135}
16136
16137// Adds the argument buffer padding argument type as a member of the struct type at the member index.
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016138// Advances both arg_buff_index and mbr_idx to next argument slots.
Bill Hollings9866cf42021-04-16 09:05:15 -040016139void CompilerMSL::add_argument_buffer_padding_type(uint32_t mbr_type_id, SPIRType &struct_type, uint32_t &mbr_idx,
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016140 uint32_t &arg_buff_index, uint32_t count)
Bill Hollings17dab612021-04-13 19:01:20 -040016141{
16142 uint32_t type_id = mbr_type_id;
16143 if (count > 1)
16144 {
16145 uint32_t ary_type_id = ir.increase_bound_by(1);
16146 auto &ary_type = set<SPIRType>(ary_type_id);
16147 ary_type = get<SPIRType>(type_id);
16148 ary_type.array.push_back(count);
16149 ary_type.array_size_literal.push_back(true);
16150 ary_type.parent_type = type_id;
16151 type_id = ary_type_id;
16152 }
16153
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016154 set_member_name(struct_type.self, mbr_idx, join("_m", arg_buff_index, "_pad"));
16155 set_extended_member_decoration(struct_type.self, mbr_idx, SPIRVCrossDecorationResourceIndexPrimary, arg_buff_index);
Bill Hollings17dab612021-04-13 19:01:20 -040016156 struct_type.member_types.push_back(type_id);
Bill Hollingsdaba0df2021-04-17 15:20:53 -040016157
16158 arg_buff_index += count;
Bill Hollings17dab612021-04-13 19:01:20 -040016159 mbr_idx++;
16160}
16161
Hans-Kristian Arntzenc3bd1362020-01-16 11:07:30 +010016162void CompilerMSL::activate_argument_buffer_resources()
16163{
16164 // For ABI compatibility, force-enable all resources which are part of argument buffers.
16165 ir.for_each_typed_id<SPIRVariable>([&](uint32_t self, const SPIRVariable &) {
16166 if (!has_decoration(self, DecorationDescriptorSet))
16167 return;
16168
16169 uint32_t desc_set = get_decoration(self, DecorationDescriptorSet);
16170 if (descriptor_set_is_argument_buffer(desc_set))
16171 active_interface_variables.insert(self);
16172 });
16173}
Hans-Kristian Arntzenc9d4f9c2020-02-24 12:47:14 +010016174
16175bool CompilerMSL::using_builtin_array() const
16176{
16177 return msl_options.force_native_arrays || is_using_builtin_array;
16178}
Hans-Kristian Arntzenbd1ee432020-10-14 14:52:18 +020016179
16180void CompilerMSL::set_combined_sampler_suffix(const char *suffix)
16181{
16182 sampler_name_suffix = suffix;
16183}
16184
16185const char *CompilerMSL::get_combined_sampler_suffix() const
16186{
16187 return sampler_name_suffix.c_str();
16188}
Hans-Kristian Arntzend62b3c22021-06-03 12:00:29 +020016189
16190void CompilerMSL::emit_block_hints(const SPIRBlock &)
16191{
16192}
Bill Hollingsebb50982021-07-13 21:22:13 -040016193
16194string CompilerMSL::additional_fixed_sample_mask_str() const
16195{
16196 char print_buffer[32];
16197 sprintf(print_buffer, "0x%x", msl_options.additional_fixed_sample_mask);
16198 return print_buffer;
16199}