blob: f678ae958ec4cf2e3c226dbbd4a71fe88ba192b4 [file] [log] [blame]
Bill Hollings103aabf2016-04-06 17:42:27 -04001/*
2 * Copyright 2015-2016 The Brenwill Workshop Ltd.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "spirv_msl.hpp"
18#include <algorithm>
19#include <numeric>
20
21using namespace spv;
22using namespace spirv_cross;
23using namespace std;
24
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020025CompilerMSL::CompilerMSL(vector<uint32_t> spirv_)
26 : CompilerGLSL(move(spirv_))
27{
28 options.vertex.fixup_clipspace = false;
Bill Hollings103aabf2016-04-06 17:42:27 -040029}
30
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020031string CompilerMSL::compile(MSLConfiguration &msl_cfg, vector<MSLVertexAttr> *p_vtx_attrs,
32 std::vector<MSLResourceBinding> *p_res_bindings)
Bill Hollings103aabf2016-04-06 17:42:27 -040033{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020034 next_metal_resource_index = MSLResourceBinding(); // Start bindings at zero
Bill Hollings8f30f072016-04-07 21:25:51 -040035
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020036 pad_type_ids_by_pad_len.clear();
Bill Hollings8f30f072016-04-07 21:25:51 -040037
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020038 msl_config = msl_cfg;
Bill Hollings8f30f072016-04-07 21:25:51 -040039
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020040 vtx_attrs_by_location.clear();
41 if (p_vtx_attrs)
42 for (auto &va : *p_vtx_attrs)
43 {
44 va.used_by_shader = false;
45 vtx_attrs_by_location[va.location] = &va;
46 }
Bill Hollings8f30f072016-04-07 21:25:51 -040047
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020048 resource_bindings.clear();
49 if (p_res_bindings)
50 {
51 resource_bindings.reserve(p_vtx_attrs->size());
52 for (auto &rb : *p_res_bindings)
53 {
54 rb.used_by_shader = false;
55 resource_bindings.push_back(&rb);
56 }
57 }
Bill Hollings8f30f072016-04-07 21:25:51 -040058
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020059 extract_builtins();
60 localize_global_variables();
61 add_interface_structs();
Bill Hollings8f30f072016-04-07 21:25:51 -040062
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020063 // Do not deal with ES-isms like precision, older extensions and such.
64 options.es = false;
65 options.version = 1;
66 backend.float_literal_suffix = false;
67 backend.uint32_t_literal_suffix = true;
68 backend.basic_int_type = "int";
69 backend.basic_uint_type = "uint";
70 backend.swizzle_is_function = false;
71 backend.shared_is_implied = false;
Bill Hollings8f30f072016-04-07 21:25:51 -040072
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020073 uint32_t pass_count = 0;
74 do
75 {
76 if (pass_count >= 3)
77 throw CompilerError("Over 3 compilation loops detected. Must be a bug!");
Bill Hollings8f30f072016-04-07 21:25:51 -040078
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020079 reset();
Bill Hollings8f30f072016-04-07 21:25:51 -040080
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020081 // Move constructor for this type is broken on GCC 4.9 ...
82 buffer = unique_ptr<ostringstream>(new ostringstream());
Bill Hollings8f30f072016-04-07 21:25:51 -040083
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020084 emit_header();
85 emit_resources();
86 emit_function_declarations();
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +020087 emit_function(get<SPIRFunction>(entry_point), 0);
Bill Hollings8f30f072016-04-07 21:25:51 -040088
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020089 pass_count++;
90 } while (force_recompile);
Bill Hollings8f30f072016-04-07 21:25:51 -040091
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020092 return buffer->str();
Bill Hollings8f30f072016-04-07 21:25:51 -040093}
94
95string CompilerMSL::compile()
96{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +020097 MSLConfiguration default_msl_cfg;
98 return compile(default_msl_cfg, nullptr, nullptr);
Bill Hollings103aabf2016-04-06 17:42:27 -040099}
100
101// Adds any builtins used by this shader to the builtin_vars collection
102void CompilerMSL::extract_builtins()
103{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200104 builtin_vars.clear();
Bill Hollings8f30f072016-04-07 21:25:51 -0400105
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200106 for (auto &id : ids)
107 {
108 if (id.get_type() == TypeVariable)
109 {
110 auto &var = id.get<SPIRVariable>();
111 auto &dec = meta[var.self].decoration;
Bill Hollings103aabf2016-04-06 17:42:27 -0400112
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200113 if (dec.builtin)
114 builtin_vars[dec.builtin_type] = var.self;
115 }
116 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400117}
118
Bill Hollings762947e2016-04-27 19:54:33 +0200119// Move the Private global variables to the entry function.
120// Non-constant variables cannot have global scope in Metal.
121void CompilerMSL::localize_global_variables()
122{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200123 auto &entry_func = get<SPIRFunction>(entry_point);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200124 auto iter = global_variables.begin();
125 while (iter != global_variables.end())
126 {
127 uint32_t gv_id = *iter;
128 auto &gbl_var = get<SPIRVariable>(gv_id);
129 if (gbl_var.storage == StorageClassPrivate)
130 {
131 entry_func.add_local_variable(gv_id);
132 iter = global_variables.erase(iter);
133 }
134 else
135 {
136 iter++;
137 }
138 }
Bill Hollings762947e2016-04-27 19:54:33 +0200139}
140
Bill Hollings103aabf2016-04-06 17:42:27 -0400141// Adds any interface structure variables needed by this shader
142void CompilerMSL::add_interface_structs()
143{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200144 auto &execution = get_entry_point();
145
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200146 stage_in_var_ids.clear();
147 qual_pos_var_name = "";
Bill Hollings78b68772016-04-11 13:28:43 -0400148
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200149 uint32_t var_id;
150 if (execution.model == ExecutionModelVertex && !vtx_attrs_by_location.empty())
151 {
152 std::set<uint32_t> vtx_bindings;
153 bind_vertex_attributes(vtx_bindings);
154 for (uint32_t vb : vtx_bindings)
155 {
156 var_id = add_interface_struct(StorageClassInput, vb);
157 if (var_id)
158 stage_in_var_ids.push_back(var_id);
159 }
160 }
161 else
162 {
163 var_id = add_interface_struct(StorageClassInput);
164 if (var_id)
165 stage_in_var_ids.push_back(var_id);
166 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400167
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200168 stage_out_var_id = add_interface_struct(StorageClassOutput);
Bill Hollings103aabf2016-04-06 17:42:27 -0400169}
170
Bill Hollings8f30f072016-04-07 21:25:51 -0400171// Iterate through the variables and populates each input vertex attribute variable
172// from the binding info provided during compiler construction, matching by location.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200173void CompilerMSL::bind_vertex_attributes(std::set<uint32_t> &bindings)
Bill Hollings103aabf2016-04-06 17:42:27 -0400174{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200175 auto &execution = get_entry_point();
176
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200177 if (execution.model == ExecutionModelVertex)
178 {
179 for (auto &id : ids)
180 {
181 if (id.get_type() == TypeVariable)
182 {
183 auto &var = id.get<SPIRVariable>();
184 auto &type = get<SPIRType>(var.basetype);
Bill Hollings103aabf2016-04-06 17:42:27 -0400185
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200186 if (var.storage == StorageClassInput && interface_variable_exists_in_entry_point(var.self) &&
Hans-Kristian Arntzenf61a5d12016-08-26 12:58:50 +0200187 !is_hidden_variable(var) && type.pointer)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200188 {
189 auto &dec = meta[var.self].decoration;
190 MSLVertexAttr *p_va = vtx_attrs_by_location[dec.location];
191 if (p_va)
192 {
193 dec.binding = p_va->msl_buffer;
194 dec.offset = p_va->msl_offset;
195 dec.array_stride = p_va->msl_stride;
196 dec.per_instance = p_va->per_instance;
Bill Hollings103aabf2016-04-06 17:42:27 -0400197
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200198 // Mark the vertex attributes that were used.
199 p_va->used_by_shader = true;
200 bindings.insert(p_va->msl_buffer);
201 }
202 }
203 }
204 }
205 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400206}
207
208// Add an the interface structure for the type of storage. For vertex inputs, each
209// binding must have its own structure, and a structure is created for vtx_binding.
210// For non-vertex input, and all outputs, the vtx_binding argument is ignored.
211// Returns the ID of the newly added variable, or zero if no variable was added.
212uint32_t CompilerMSL::add_interface_struct(StorageClass storage, uint32_t vtx_binding)
213{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200214 auto &execution = get_entry_point();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200215 bool incl_builtins = (storage == StorageClassOutput);
216 bool match_binding = (execution.model == ExecutionModelVertex) && (storage == StorageClassInput);
Bill Hollings103aabf2016-04-06 17:42:27 -0400217
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200218 // Accumulate the variables that should appear in the interface struct
219 vector<SPIRVariable *> vars;
220 for (auto &id : ids)
221 {
222 if (id.get_type() == TypeVariable)
223 {
224 auto &var = id.get<SPIRVariable>();
225 auto &type = get<SPIRType>(var.basetype);
226 auto &dec = meta[var.self].decoration;
Bill Hollings103aabf2016-04-06 17:42:27 -0400227
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200228 if (var.storage == storage && interface_variable_exists_in_entry_point(var.self) &&
Hans-Kristian Arntzenf61a5d12016-08-26 12:58:50 +0200229 !is_hidden_variable(var, incl_builtins) && (!match_binding || (vtx_binding == dec.binding)) &&
230 type.pointer)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200231 {
232 vars.push_back(&var);
233 }
234 }
235 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400236
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200237 if (vars.empty())
238 {
239 return 0;
240 } // Leave if no variables qualify
Bill Hollings103aabf2016-04-06 17:42:27 -0400241
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200242 // Add a new typed variable for this interface structure.
243 // The initializer expression is allocated here, but populated when the function
244 // declaraion is emitted, because it is cleared after each compilation pass.
245 uint32_t next_id = increase_bound_by(3);
246 uint32_t ib_type_id = next_id++;
247 auto &ib_type = set<SPIRType>(ib_type_id);
248 ib_type.basetype = SPIRType::Struct;
249 ib_type.storage = storage;
250 set_decoration(ib_type.self, DecorationBlock);
Bill Hollings103aabf2016-04-06 17:42:27 -0400251
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200252 uint32_t ib_var_id = next_id++;
253 auto &var = set<SPIRVariable>(ib_var_id, ib_type_id, storage, 0);
254 var.initializer = next_id++;
Bill Hollings103aabf2016-04-06 17:42:27 -0400255
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200256 // Set the binding of the variable and mark if packed (used only with vertex inputs)
257 auto &var_dec = meta[ib_var_id].decoration;
258 var_dec.binding = vtx_binding;
259 ib_type.is_packed = (execution.model == ExecutionModelVertex && storage == StorageClassInput &&
260 var_dec.binding != msl_config.vtx_attr_stage_in_binding);
Bill Hollings103aabf2016-04-06 17:42:27 -0400261
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200262 string ib_var_ref;
263 if (storage == StorageClassInput)
264 ib_var_ref = ib_type.is_packed ? stage_in_var_name + convert_to_string(vtx_binding) : stage_in_var_name;
Bill Hollings103aabf2016-04-06 17:42:27 -0400265
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200266 if (storage == StorageClassOutput)
267 {
268 ib_var_ref = stage_out_var_name;
Bill Hollings103aabf2016-04-06 17:42:27 -0400269
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200270 // Add the output interface struct as a local variable to the entry function,
271 // and force the entry function to return the output interface struct from
272 // any blocks that perform a function return.
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200273 auto &entry_func = get<SPIRFunction>(entry_point);
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200274 entry_func.add_local_variable(ib_var_id);
275 for (auto &blk_id : entry_func.blocks)
276 {
277 auto &blk = get<SPIRBlock>(blk_id);
278 if (blk.terminator == SPIRBlock::Return)
279 blk.return_value = ib_var_id;
280 }
281 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400282
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200283 set_name(ib_type_id, get_entry_point_name() + "_" + ib_var_ref);
284 set_name(ib_var_id, ib_var_ref);
Bill Hollings103aabf2016-04-06 17:42:27 -0400285
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200286 size_t struct_size = 0;
287 bool first_elem = true;
288 for (auto p_var : vars)
289 {
290 // For packed vertex attributes, copy the attribute characteristics to the parent
291 // structure (all components have same vertex attribute characteristics except offset),
292 // and add a reference to the vertex index builtin to the parent struct variable name.
293 if (ib_type.is_packed && first_elem)
294 {
295 auto &elem_dec = meta[p_var->self].decoration;
296 var_dec.binding = elem_dec.binding;
297 var_dec.array_stride = elem_dec.array_stride;
298 var_dec.per_instance = elem_dec.per_instance;
299 ib_var_ref += "[" + get_vtx_idx_var_name(var_dec.per_instance) + "]";
300 first_elem = false;
301 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400302
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200303 auto &type = get<SPIRType>(p_var->basetype);
304 auto &type_dec = meta[type.self].decoration;
Bill Hollings103aabf2016-04-06 17:42:27 -0400305
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200306 if (type_dec.decoration_flags & (1ull << DecorationBlock))
307 {
308 // Flatten the struct members into the interface struct
309 uint32_t i = 0;
310 for (auto &member : type.member_types)
311 {
312 // If needed, add a padding member to the struct to align to the next member's offset.
313 uint32_t mbr_offset = get_member_decoration(type.self, i, DecorationOffset);
314 struct_size = pad_to_offset(ib_type, (var_dec.offset + mbr_offset), (uint32_t)struct_size);
Bill Hollings103aabf2016-04-06 17:42:27 -0400315
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200316 // Add a reference to the member to the interface struct.
317 auto &membertype = get<SPIRType>(member);
318 uint32_t ib_mbr_idx = (uint32_t)ib_type.member_types.size();
319 ib_type.member_types.push_back(membertype.self);
Bill Hollings103aabf2016-04-06 17:42:27 -0400320
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200321 // Give the member a name, and assign it an offset within the struct.
322 string mbr_name = to_member_name(type, i);
323 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
324 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationOffset, (uint32_t)struct_size);
325 struct_size = get_declared_struct_size(ib_type);
Bill Hollings103aabf2016-04-06 17:42:27 -0400326
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200327 // Update the original variable reference to include the structure reference
328 string qual_var_name = ib_var_ref + "." + mbr_name;
329 set_member_name(type.self, i, qual_var_name);
Bill Hollings103aabf2016-04-06 17:42:27 -0400330
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200331 // Copy the variable location from the original variable to the member
332 uint32_t locn = get_member_decoration(type.self, i, DecorationLocation);
333 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, locn);
Bill Hollings103aabf2016-04-06 17:42:27 -0400334
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200335 // Mark the member as builtin if needed
336 BuiltIn builtin;
337 if (is_member_builtin(type, i, &builtin))
338 {
339 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, builtin);
340 if (builtin == BuiltInPosition)
341 qual_pos_var_name = qual_var_name;
342 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400343
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200344 i++;
345 }
346 }
347 else
348 {
349 // If needed, add a padding member to the struct to align to the next member's offset.
350 struct_size = pad_to_offset(ib_type, var_dec.offset, (uint32_t)struct_size);
Bill Hollings103aabf2016-04-06 17:42:27 -0400351
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200352 // Add a reference to the variable type to the interface struct.
353 uint32_t ib_mbr_idx = (uint32_t)ib_type.member_types.size();
354 ib_type.member_types.push_back(type.self);
Bill Hollings103aabf2016-04-06 17:42:27 -0400355
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200356 // Give the member a name, and assign it an offset within the struct.
357 string mbr_name = to_name(p_var->self);
358 set_member_name(ib_type.self, ib_mbr_idx, mbr_name);
359 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationOffset, (uint32_t)struct_size);
360 struct_size = get_declared_struct_size(ib_type);
Bill Hollings103aabf2016-04-06 17:42:27 -0400361
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200362 // Update the original variable reference to include the structure reference
363 string qual_var_name = ib_var_ref + "." + mbr_name;
364 meta[p_var->self].decoration.alias = qual_var_name;
Bill Hollings103aabf2016-04-06 17:42:27 -0400365
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200366 // Copy the variable location from the original variable to the member
367 auto &dec = meta[p_var->self].decoration;
368 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationLocation, dec.location);
Bill Hollings103aabf2016-04-06 17:42:27 -0400369
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200370 // Mark the member as builtin if needed
371 if (is_builtin_variable(*p_var))
372 {
373 set_member_decoration(ib_type.self, ib_mbr_idx, DecorationBuiltIn, dec.builtin_type);
374 if (dec.builtin_type == BuiltInPosition)
375 qual_pos_var_name = qual_var_name;
376 }
377 }
378 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400379
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200380 if (!ib_type.is_packed)
381 {
382 // Sort the members of the interface structure, unless this is packed input
383 MemberSorterByLocation memberSorter(ib_type, meta[ib_type.self]);
384 memberSorter.sort();
385 }
386
387 return ib_var_id;
Bill Hollings103aabf2016-04-06 17:42:27 -0400388}
389
Bill Hollings103aabf2016-04-06 17:42:27 -0400390// Emits the file header info
391void CompilerMSL::emit_header()
392{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200393 statement("#include <metal_stdlib>");
394 statement("#include <simd/simd.h>");
395 statement("");
396 statement("using namespace metal;");
397 statement("");
Bill Hollings103aabf2016-04-06 17:42:27 -0400398}
399
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200400void CompilerMSL::emit_resources()
401{
Bill Hollings103aabf2016-04-06 17:42:27 -0400402
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200403 // Output all basic struct types which are not Block or BufferBlock as these are declared inplace
404 // when such variables are instantiated.
405 for (auto &id : ids)
406 {
407 if (id.get_type() == TypeType)
408 {
409 auto &type = id.get<SPIRType>();
410 if (type.basetype == SPIRType::Struct && type.array.empty() && !type.pointer &&
411 (meta[type.self].decoration.decoration_flags &
412 ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock))) == 0)
413 {
414 emit_struct(type);
415 }
416 }
417 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400418
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200419 // Output Uniform buffers and constants
420 for (auto &id : ids)
421 {
422 if (id.get_type() == TypeVariable)
423 {
424 auto &var = id.get<SPIRVariable>();
425 auto &type = get<SPIRType>(var.basetype);
Bill Hollings103aabf2016-04-06 17:42:27 -0400426
Hans-Kristian Arntzend5dc5f32016-07-05 13:21:26 +0200427 if (var.storage != StorageClassFunction && type.pointer &&
428 (type.storage == StorageClassUniform || type.storage == StorageClassUniformConstant ||
429 type.storage == StorageClassPushConstant) &&
Hans-Kristian Arntzenf61a5d12016-08-26 12:58:50 +0200430 !is_hidden_variable(var) && (meta[type.self].decoration.decoration_flags &
431 ((1ull << DecorationBlock) | (1ull << DecorationBufferBlock))))
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200432 {
433 emit_struct(type);
434 }
435 }
436 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400437
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200438 // Output interface blocks.
439 for (uint32_t var_id : stage_in_var_ids)
440 emit_interface_block(var_id);
Bill Hollings103aabf2016-04-06 17:42:27 -0400441
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200442 emit_interface_block(stage_out_var_id);
Bill Hollings103aabf2016-04-06 17:42:27 -0400443
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200444 // TODO: Consolidate and output loose uniforms into an input struct
Bill Hollings103aabf2016-04-06 17:42:27 -0400445}
446
447// Emit a structure declaration for the specified interface variable.
448void CompilerMSL::emit_interface_block(uint32_t ib_var_id)
449{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200450 if (ib_var_id)
451 {
452 auto &ib_var = get<SPIRVariable>(ib_var_id);
453 auto &ib_type = get<SPIRType>(ib_var.basetype);
454 emit_struct(ib_type);
455 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400456}
457
458// Output a declaration statement for each function.
459void CompilerMSL::emit_function_declarations()
460{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200461 for (auto &id : ids)
462 if (id.get_type() == TypeFunction)
463 {
464 auto &func = id.get<SPIRFunction>();
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200465 if (func.self != entry_point)
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200466 emit_function_prototype(func, true);
467 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400468
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200469 statement("");
Bill Hollings103aabf2016-04-06 17:42:27 -0400470}
471
472void CompilerMSL::emit_function_prototype(SPIRFunction &func, uint64_t)
473{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200474 emit_function_prototype(func, false);
Bill Hollings103aabf2016-04-06 17:42:27 -0400475}
476
477// Emits the declaration signature of the specified function.
478// If this is the entry point function, Metal-specific return value and function arguments are added.
479void CompilerMSL::emit_function_prototype(SPIRFunction &func, bool is_decl)
480{
Hans-Kristian Arntzen6aa20072016-05-23 12:25:09 +0200481 local_variable_names = resource_names;
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200482 string decl;
Bill Hollings103aabf2016-04-06 17:42:27 -0400483
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200484 processing_entry_point = (func.self == entry_point);
Bill Hollings103aabf2016-04-06 17:42:27 -0400485
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200486 auto &type = get<SPIRType>(func.return_type);
487 decl += func_type_decl(type);
488 decl += " ";
489 decl += clean_func_name(to_name(func.self));
Bill Hollings103aabf2016-04-06 17:42:27 -0400490
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200491 decl += "(";
Bill Hollings103aabf2016-04-06 17:42:27 -0400492
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200493 if (processing_entry_point)
494 {
495 decl += entry_point_args(!func.arguments.empty());
Bill Hollings103aabf2016-04-06 17:42:27 -0400496
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200497 // If entry point function has a output interface struct, set its initializer.
498 // This is done at this late stage because the initialization expression is
499 // cleared after each compilation pass.
500 if (stage_out_var_id)
501 {
502 auto &so_var = get<SPIRVariable>(stage_out_var_id);
503 auto &so_type = get<SPIRType>(so_var.basetype);
504 set<SPIRExpression>(so_var.initializer, "{}", so_type.self, true);
505 }
506 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400507
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200508 for (auto &arg : func.arguments)
509 {
Hans-Kristian Arntzen6aa20072016-05-23 12:25:09 +0200510 add_local_variable_name(arg.id);
Bill Hollings103aabf2016-04-06 17:42:27 -0400511
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200512 decl += "thread " + argument_decl(arg);
513 if (&arg != &func.arguments.back())
514 decl += ", ";
Bill Hollings103aabf2016-04-06 17:42:27 -0400515
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200516 // Hold a pointer to the parameter so we can invalidate the readonly field if needed.
517 auto *var = maybe_get<SPIRVariable>(arg.id);
518 if (var)
519 var->parameter = &arg;
520 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400521
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200522 decl += ")";
523 statement(decl, (is_decl ? ";" : ""));
Bill Hollings103aabf2016-04-06 17:42:27 -0400524}
525
526// Emit a texture operation
527void CompilerMSL::emit_texture_op(const Instruction &i)
528{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200529 auto ops = stream(i);
530 auto op = static_cast<Op>(i.op);
531 uint32_t length = i.length;
Bill Hollings103aabf2016-04-06 17:42:27 -0400532
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200533 if (i.offset + length > spirv.size())
534 throw CompilerError("Compiler::compile() opcode out of range.");
Bill Hollings103aabf2016-04-06 17:42:27 -0400535
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200536 uint32_t result_type = ops[0];
537 uint32_t id = ops[1];
538 uint32_t img = ops[2];
539 uint32_t coord = ops[3];
540 uint32_t comp = 0;
541 bool gather = false;
542 bool fetch = false;
543 const uint32_t *opt = nullptr;
Bill Hollings103aabf2016-04-06 17:42:27 -0400544
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200545 switch (op)
546 {
547 case OpImageSampleDrefImplicitLod:
548 case OpImageSampleDrefExplicitLod:
549 opt = &ops[5];
550 length -= 5;
551 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400552
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200553 case OpImageSampleProjDrefImplicitLod:
554 case OpImageSampleProjDrefExplicitLod:
555 opt = &ops[5];
556 length -= 5;
557 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400558
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200559 case OpImageDrefGather:
560 opt = &ops[5];
561 gather = true;
562 length -= 5;
563 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400564
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200565 case OpImageGather:
566 comp = ops[4];
567 opt = &ops[5];
568 gather = true;
569 length -= 5;
570 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400571
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200572 case OpImageFetch:
573 fetch = true;
574 opt = &ops[4];
575 length -= 4;
576 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400577
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200578 case OpImageSampleImplicitLod:
579 case OpImageSampleExplicitLod:
580 case OpImageSampleProjImplicitLod:
581 case OpImageSampleProjExplicitLod:
582 default:
583 opt = &ops[4];
584 length -= 4;
585 break;
586 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400587
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200588 uint32_t bias = 0;
589 uint32_t lod = 0;
590 uint32_t grad_x = 0;
591 uint32_t grad_y = 0;
592 uint32_t coffset = 0;
593 uint32_t offset = 0;
594 uint32_t coffsets = 0;
595 uint32_t sample = 0;
596 uint32_t flags = 0;
Bill Hollings103aabf2016-04-06 17:42:27 -0400597
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200598 if (length)
599 {
600 flags = *opt;
601 opt++;
602 length--;
603 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400604
Hans-Kristian Arntzen5ea59bd2016-05-23 13:30:02 +0200605 auto test = [&](uint32_t &v, uint32_t flag) {
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200606 if (length && (flags & flag))
607 {
608 v = *opt++;
609 length--;
610 }
611 };
Bill Hollings103aabf2016-04-06 17:42:27 -0400612
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200613 test(bias, ImageOperandsBiasMask);
614 test(lod, ImageOperandsLodMask);
615 test(grad_x, ImageOperandsGradMask);
616 test(grad_y, ImageOperandsGradMask);
617 test(coffset, ImageOperandsConstOffsetMask);
618 test(offset, ImageOperandsOffsetMask);
619 test(coffsets, ImageOperandsConstOffsetsMask);
620 test(sample, ImageOperandsSampleMask);
Bill Hollings762947e2016-04-27 19:54:33 +0200621
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200622 auto &img_type = expression_type(img).image;
Bill Hollings103aabf2016-04-06 17:42:27 -0400623
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200624 // Texture reference
625 string expr = to_expression(img);
Bill Hollings103aabf2016-04-06 17:42:27 -0400626
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200627 // Texture function and sampler
628 if (fetch)
629 {
630 expr += ".read(";
631 }
632 else
633 {
634 expr += std::string(".") + (gather ? "gather" : "sample") + "(" + to_sampler_expression(img) + ", ";
635 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400636
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200637 // Add texture coordinates
638 bool forward = should_forward(coord);
639 auto coord_expr = to_expression(coord);
640 string tex_coords = coord_expr;
641 string array_coord;
Bill Hollings103aabf2016-04-06 17:42:27 -0400642
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200643 switch (img_type.dim)
644 {
645 case spv::DimBuffer:
646 break;
647 case Dim1D:
648 if (img_type.arrayed)
649 {
650 tex_coords = coord_expr + ".x";
651 array_coord = coord_expr + ".y";
652 remove_duplicate_swizzle(tex_coords);
653 remove_duplicate_swizzle(array_coord);
654 }
655 else
656 {
657 tex_coords = coord_expr + ".x";
658 }
659 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400660
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200661 case Dim2D:
662 if (msl_config.flip_frag_y)
663 {
664 string coord_x = coord_expr + ".x";
665 remove_duplicate_swizzle(coord_x);
666 string coord_y = coord_expr + ".y";
667 remove_duplicate_swizzle(coord_y);
668 tex_coords = "float2(" + coord_x + ", (1.0 - " + coord_y + "))";
669 }
670 else
671 {
672 tex_coords = coord_expr + ".xy";
673 remove_duplicate_swizzle(tex_coords);
674 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400675
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200676 if (img_type.arrayed)
677 {
678 array_coord = coord_expr + ".z";
679 remove_duplicate_swizzle(array_coord);
680 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400681
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200682 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400683
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200684 case Dim3D:
685 case DimCube:
686 if (msl_config.flip_frag_y)
687 {
688 string coord_x = coord_expr + ".x";
689 remove_duplicate_swizzle(coord_x);
690 string coord_y = coord_expr + ".y";
691 remove_duplicate_swizzle(coord_y);
692 string coord_z = coord_expr + ".z";
693 remove_duplicate_swizzle(coord_z);
694 tex_coords = "float3(" + coord_x + ", (1.0 - " + coord_y + "), " + coord_z + ")";
695 }
696 else
697 {
698 tex_coords = coord_expr + ".xyz";
699 remove_duplicate_swizzle(tex_coords);
700 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400701
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200702 if (img_type.arrayed)
703 {
704 array_coord = coord_expr + ".w";
705 remove_duplicate_swizzle(array_coord);
706 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400707
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200708 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400709
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200710 default:
711 break;
712 }
713 expr += tex_coords;
Bill Hollings103aabf2016-04-06 17:42:27 -0400714
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200715 // Add texture array index
716 if (!array_coord.empty())
717 expr += ", " + array_coord;
Bill Hollings103aabf2016-04-06 17:42:27 -0400718
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200719 // LOD Options
720 if (bias)
721 {
722 forward = forward && should_forward(bias);
723 expr += ", bias(" + to_expression(bias) + ")";
724 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400725
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200726 if (lod)
727 {
728 forward = forward && should_forward(lod);
729 if (fetch)
730 {
731 expr += ", " + to_expression(lod);
732 }
733 else
734 {
735 expr += ", level(" + to_expression(lod) + ")";
736 }
737 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400738
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200739 if (grad_x || grad_y)
740 {
741 forward = forward && should_forward(grad_x);
742 forward = forward && should_forward(grad_y);
743 string grad_opt;
744 switch (img_type.dim)
745 {
746 case Dim2D:
747 grad_opt = "2d";
748 break;
749 case Dim3D:
750 grad_opt = "3d";
751 break;
752 case DimCube:
753 grad_opt = "cube";
754 break;
755 default:
756 grad_opt = "unsupported_gradient_dimension";
757 break;
758 }
759 expr += ", gradient" + grad_opt + "(" + to_expression(grad_x) + ", " + to_expression(grad_y) + ")";
760 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400761
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200762 // Add offsets
763 string offset_expr;
764 if (coffset)
765 {
766 forward = forward && should_forward(coffset);
767 offset_expr = to_expression(coffset);
768 }
769 else if (offset)
770 {
771 forward = forward && should_forward(offset);
772 offset_expr = to_expression(offset);
773 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400774
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200775 if (!offset_expr.empty())
776 {
777 switch (img_type.dim)
778 {
779 case Dim2D:
780 if (msl_config.flip_frag_y)
781 {
782 string coord_x = offset_expr + ".x";
783 remove_duplicate_swizzle(coord_x);
784 string coord_y = offset_expr + ".y";
785 remove_duplicate_swizzle(coord_y);
786 offset_expr = "float2(" + coord_x + ", (1.0 - " + coord_y + "))";
787 }
788 else
789 {
790 offset_expr = offset_expr + ".xy";
791 remove_duplicate_swizzle(offset_expr);
792 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400793
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200794 expr += ", " + offset_expr;
795 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400796
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200797 case Dim3D:
798 if (msl_config.flip_frag_y)
799 {
800 string coord_x = offset_expr + ".x";
801 remove_duplicate_swizzle(coord_x);
802 string coord_y = offset_expr + ".y";
803 remove_duplicate_swizzle(coord_y);
804 string coord_z = offset_expr + ".z";
805 remove_duplicate_swizzle(coord_z);
806 offset_expr = "float3(" + coord_x + ", (1.0 - " + coord_y + "), " + coord_z + ")";
807 }
808 else
809 {
810 offset_expr = offset_expr + ".xyz";
811 remove_duplicate_swizzle(offset_expr);
812 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400813
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200814 expr += ", " + offset_expr;
815 break;
Bill Hollings103aabf2016-04-06 17:42:27 -0400816
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200817 default:
818 break;
819 }
820 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400821
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200822 if (comp)
823 {
824 forward = forward && should_forward(comp);
825 expr += ", " + to_expression(comp);
826 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400827
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200828 expr += ")";
Bill Hollings103aabf2016-04-06 17:42:27 -0400829
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200830 emit_op(result_type, id, expr, forward, false);
Bill Hollings103aabf2016-04-06 17:42:27 -0400831}
832
Bill Hollings5aafb282016-04-23 21:47:41 -0400833// Establish sampled image as expression object and assign the sampler to it.
834void CompilerMSL::emit_sampled_image_op(uint32_t result_type, uint32_t result_id, uint32_t image_id, uint32_t samp_id)
835{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200836 set<SPIRExpression>(result_id, to_expression(image_id), result_type, true);
837 meta[result_id].sampler = samp_id;
Bill Hollings5aafb282016-04-23 21:47:41 -0400838}
839
840// If the ID represents a sampled image that has been assigned a sampler already,
841// generate an expression for the sampler, otherwise generate a fake sampler name
842// by appending a suffix to the expression constructed from the ID.
843string CompilerMSL::to_sampler_expression(uint32_t id)
844{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200845 uint32_t samp_id = meta[id].sampler;
846 return samp_id ? to_expression(samp_id) : to_expression(id) + sampler_name_suffix;
Bill Hollings5aafb282016-04-23 21:47:41 -0400847}
848
Bill Hollings103aabf2016-04-06 17:42:27 -0400849// Called automatically at the end of the entry point function
850void CompilerMSL::emit_fixup()
851{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200852 auto &execution = get_entry_point();
853
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200854 if ((execution.model == ExecutionModelVertex) && stage_out_var_id && !qual_pos_var_name.empty())
855 {
856 if (options.vertex.fixup_clipspace)
857 {
858 const char *suffix = backend.float_literal_suffix ? "f" : "";
859 statement(qual_pos_var_name, ".z = 2.0", suffix, " * ", qual_pos_var_name, ".z - ", qual_pos_var_name,
860 ".w;");
861 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400862
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200863 if (msl_config.flip_vert_y)
864 statement(qual_pos_var_name, ".y = -(", qual_pos_var_name, ".y);", " // Invert Y-axis for Metal");
865 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400866}
867
868// Returns a declaration for a structure member.
869string CompilerMSL::member_decl(const SPIRType &type, const SPIRType &membertype, uint32_t index)
870{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200871 bool should_pack = type.is_packed && is_vector(membertype);
872 return join((should_pack ? "packed_" : ""), type_to_glsl(membertype), " ", to_member_name(type, index),
873 type_to_array_glsl(membertype), member_attribute_qualifier(type, index));
Bill Hollings103aabf2016-04-06 17:42:27 -0400874}
875
876// Return a MSL qualifier for the specified function attribute member
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200877string CompilerMSL::member_attribute_qualifier(const SPIRType &type, uint32_t index)
878{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +0200879 auto &execution = get_entry_point();
Bill Hollings103aabf2016-04-06 17:42:27 -0400880
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200881 BuiltIn builtin;
882 bool is_builtin = is_member_builtin(type, index, &builtin);
Bill Hollings103aabf2016-04-06 17:42:27 -0400883
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200884 // Vertex function inputs
885 if (execution.model == ExecutionModelVertex && type.storage == StorageClassInput)
886 {
887 if (is_builtin)
888 {
889 switch (builtin)
890 {
891 case BuiltInVertexId:
892 case BuiltInVertexIndex:
893 case BuiltInInstanceId:
894 case BuiltInInstanceIndex:
895 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -0400896
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200897 default:
898 return "";
899 }
900 }
901 uint32_t locn = get_ordered_member_location(type.self, index);
902 return string(" [[attribute(") + convert_to_string(locn) + ")]]";
903 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400904
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200905 // Vertex function outputs
906 if (execution.model == ExecutionModelVertex && type.storage == StorageClassOutput)
907 {
908 if (is_builtin)
909 {
910 switch (builtin)
911 {
912 case BuiltInClipDistance:
913 return " /* [[clip_distance]] built-in not yet supported under Metal. */";
Bill Hollings103aabf2016-04-06 17:42:27 -0400914
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200915 case BuiltInPointSize: // Must output only if really rendering points
916 return msl_config.is_rendering_points ? (string(" [[") + builtin_qualifier(builtin) + "]]") : "";
Bill Hollings103aabf2016-04-06 17:42:27 -0400917
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200918 case BuiltInPosition:
919 case BuiltInLayer:
920 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -0400921
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200922 default:
923 return "";
924 }
925 }
926 uint32_t locn = get_ordered_member_location(type.self, index);
927 return string(" [[user(locn") + convert_to_string(locn) + ")]]";
928 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400929
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200930 // Fragment function inputs
931 if (execution.model == ExecutionModelFragment && type.storage == StorageClassInput)
932 {
933 if (is_builtin)
934 {
935 switch (builtin)
936 {
937 case BuiltInFrontFacing:
938 case BuiltInPointCoord:
939 case BuiltInSamplePosition:
940 case BuiltInSampleId:
941 case BuiltInSampleMask:
942 case BuiltInLayer:
943 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -0400944
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200945 default:
946 return "";
947 }
948 }
949 uint32_t locn = get_ordered_member_location(type.self, index);
950 return string(" [[user(locn") + convert_to_string(locn) + ")]]";
951 }
Bill Hollings103aabf2016-04-06 17:42:27 -0400952
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200953 // Fragment function outputs
954 if (execution.model == ExecutionModelFragment && type.storage == StorageClassOutput)
955 {
956 if (is_builtin)
957 {
958 switch (builtin)
959 {
960 case BuiltInSampleMask:
961 case BuiltInFragDepth:
962 return string(" [[") + builtin_qualifier(builtin) + "]]";
Bill Hollings103aabf2016-04-06 17:42:27 -0400963
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200964 default:
965 return "";
966 }
967 }
968 return "";
969 }
970
971 return "";
Bill Hollings103aabf2016-04-06 17:42:27 -0400972}
973
974// Returns the location decoration of the member with the specified index in the specified
975// type, or the value of the member index if the location has not been specified.
976// This function assumes the members are ordered in their location order.
977// This can be ensured using the MemberSorterByLocation class.
978uint32_t CompilerMSL::get_ordered_member_location(uint32_t type_id, uint32_t index)
979{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200980 return max(get_member_decoration(type_id, index, DecorationLocation), index);
Bill Hollings103aabf2016-04-06 17:42:27 -0400981}
982
983string CompilerMSL::constant_expression(const SPIRConstant &c)
984{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +0200985 if (!c.subconstants.empty())
986 {
987 // Handles Arrays and structures.
988 string res = "{";
989 for (auto &elem : c.subconstants)
990 {
991 res += constant_expression(get<SPIRConstant>(elem));
992 if (&elem != &c.subconstants.back())
993 res += ", ";
994 }
995 res += "}";
996 return res;
997 }
998 else if (c.columns() == 1)
999 {
1000 return constant_expression_vector(c, 0);
1001 }
1002 else
1003 {
1004 string res = type_to_glsl(get<SPIRType>(c.constant_type)) + "(";
1005 for (uint32_t col = 0; col < c.columns(); col++)
1006 {
1007 res += constant_expression_vector(c, col);
1008 if (col + 1 < c.columns())
1009 res += ", ";
1010 }
1011 res += ")";
1012 return res;
1013 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001014}
1015
1016// Returns the type declaration for a function, including the
1017// entry type if the current function is the entry point function
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001018string CompilerMSL::func_type_decl(SPIRType &type)
Bill Hollings103aabf2016-04-06 17:42:27 -04001019{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +02001020 auto &execution = get_entry_point();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001021 // The regular function return type. If not processing the entry point function, that's all we need
1022 string return_type = type_to_glsl(type);
1023 if (!processing_entry_point)
1024 return return_type;
Bill Hollings103aabf2016-04-06 17:42:27 -04001025
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001026 // If an outgoing interface block has been defined, override the entry point return type
1027 if (stage_out_var_id)
1028 {
1029 auto &so_var = get<SPIRVariable>(stage_out_var_id);
1030 auto &so_type = get<SPIRType>(so_var.basetype);
1031 return_type = type_to_glsl(so_type);
1032 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001033
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001034 // Prepend a entry type, based on the execution model
1035 string entry_type;
1036 switch (execution.model)
1037 {
1038 case ExecutionModelVertex:
1039 entry_type = "vertex";
1040 break;
1041 case ExecutionModelFragment:
1042 entry_type = (execution.flags & (1ull << ExecutionModeEarlyFragmentTests)) ?
1043 "fragment [[ early_fragment_tests ]]" :
1044 "fragment";
1045 break;
1046 case ExecutionModelGLCompute:
1047 case ExecutionModelKernel:
1048 entry_type = "kernel";
1049 break;
1050 default:
1051 entry_type = "unknown";
1052 break;
1053 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001054
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001055 return entry_type + " " + return_type;
Bill Hollings103aabf2016-04-06 17:42:27 -04001056}
1057
1058// Ensures the function name is not "main", which is illegal in MSL
1059string CompilerMSL::clean_func_name(string func_name)
1060{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001061 static std::string _clean_msl_main_func_name = "mmain";
1062 return (func_name == "main") ? _clean_msl_main_func_name : func_name;
Bill Hollings103aabf2016-04-06 17:42:27 -04001063}
1064
1065// Returns a string containing a comma-delimited list of args for the entry point function
1066string CompilerMSL::entry_point_args(bool append_comma)
1067{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +02001068 auto &execution = get_entry_point();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001069 string ep_args;
Bill Hollings103aabf2016-04-06 17:42:27 -04001070
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001071 // Stage-in structures
1072 for (uint32_t var_id : stage_in_var_ids)
1073 {
1074 auto &var = get<SPIRVariable>(var_id);
1075 auto &type = get<SPIRType>(var.basetype);
1076 auto &dec = meta[var.self].decoration;
Bill Hollings103aabf2016-04-06 17:42:27 -04001077
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001078 bool use_stage_in =
1079 (execution.model != ExecutionModelVertex || dec.binding == msl_config.vtx_attr_stage_in_binding);
Bill Hollings103aabf2016-04-06 17:42:27 -04001080
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001081 if (!ep_args.empty())
1082 ep_args += ", ";
1083 if (use_stage_in)
1084 ep_args += type_to_glsl(type) + " " + to_name(var.self) + " [[stage_in]]";
1085 else
1086 ep_args += "device " + type_to_glsl(type) + "* " + to_name(var.self) + " [[buffer(" +
1087 convert_to_string(dec.binding) + ")]]";
1088 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001089
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001090 // Uniforms
1091 for (auto &id : ids)
1092 {
1093 if (id.get_type() == TypeVariable)
1094 {
1095 auto &var = id.get<SPIRVariable>();
1096 auto &type = get<SPIRType>(var.basetype);
Bill Hollings103aabf2016-04-06 17:42:27 -04001097
Hans-Kristian Arntzenf61a5d12016-08-26 12:58:50 +02001098 if (is_hidden_variable(var, true))
1099 continue;
1100
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001101 if (var.storage == StorageClassUniform || var.storage == StorageClassUniformConstant ||
1102 var.storage == StorageClassPushConstant)
1103 {
1104 switch (type.basetype)
1105 {
1106 case SPIRType::Struct:
1107 if (!ep_args.empty())
1108 ep_args += ", ";
1109 ep_args += "constant " + type_to_glsl(type) + "& " + to_name(var.self);
1110 ep_args += " [[buffer(" + convert_to_string(get_metal_resource_index(var, type.basetype)) + ")]]";
1111 break;
1112 case SPIRType::Sampler:
1113 if (!ep_args.empty())
1114 ep_args += ", ";
1115 ep_args += type_to_glsl(type) + " " + to_name(var.self);
1116 ep_args += " [[sampler(" + convert_to_string(get_metal_resource_index(var, type.basetype)) + ")]]";
1117 break;
1118 case SPIRType::Image:
1119 if (!ep_args.empty())
1120 ep_args += ", ";
1121 ep_args += type_to_glsl(type) + " " + to_name(var.self);
1122 ep_args += " [[texture(" + convert_to_string(get_metal_resource_index(var, type.basetype)) + ")]]";
1123 break;
1124 case SPIRType::SampledImage:
1125 if (!ep_args.empty())
1126 ep_args += ", ";
1127 ep_args += type_to_glsl(type) + " " + to_name(var.self);
1128 ep_args +=
1129 " [[texture(" + convert_to_string(get_metal_resource_index(var, SPIRType::Image)) + ")]]";
1130 if (type.image.dim != DimBuffer)
1131 {
1132 ep_args += ", sampler " + to_sampler_expression(var.self);
1133 ep_args +=
1134 " [[sampler(" + convert_to_string(get_metal_resource_index(var, SPIRType::Sampler)) + ")]]";
1135 }
1136 break;
1137 default:
1138 break;
1139 }
1140 }
1141 if (var.storage == StorageClassInput && is_builtin_variable(var))
1142 {
1143 if (!ep_args.empty())
1144 ep_args += ", ";
1145 BuiltIn bi_type = meta[var.self].decoration.builtin_type;
1146 ep_args += builtin_type_decl(bi_type) + " " + to_expression(var.self);
1147 ep_args += " [[" + builtin_qualifier(bi_type) + "]]";
1148 }
1149 }
1150 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001151
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001152 if (!ep_args.empty() && append_comma)
1153 ep_args += ", ";
Bill Hollings103aabf2016-04-06 17:42:27 -04001154
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001155 return ep_args;
Bill Hollings103aabf2016-04-06 17:42:27 -04001156}
1157
1158// Returns the Metal index of the resource of the specified type as used by the specified variable.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001159uint32_t CompilerMSL::get_metal_resource_index(SPIRVariable &var, SPIRType::BaseType basetype)
1160{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +02001161 auto &execution = get_entry_point();
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001162 auto &var_dec = meta[var.self].decoration;
1163 uint32_t var_desc_set = (var.storage == StorageClassPushConstant) ? kPushConstDescSet : var_dec.set;
1164 uint32_t var_binding = (var.storage == StorageClassPushConstant) ? kPushConstBinding : var_dec.binding;
Bill Hollings103aabf2016-04-06 17:42:27 -04001165
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001166 // If a matching binding has been specified, find and use it
1167 for (auto p_res_bind : resource_bindings)
1168 {
1169 if (p_res_bind->stage == execution.model && p_res_bind->desc_set == var_desc_set &&
1170 p_res_bind->binding == var_binding)
1171 {
Bill Hollings103aabf2016-04-06 17:42:27 -04001172
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001173 p_res_bind->used_by_shader = true;
1174 switch (basetype)
1175 {
1176 case SPIRType::Struct:
1177 return p_res_bind->msl_buffer;
1178 case SPIRType::Image:
1179 return p_res_bind->msl_texture;
1180 case SPIRType::Sampler:
1181 return p_res_bind->msl_sampler;
1182 default:
1183 return 0;
1184 }
1185 }
1186 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001187
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001188 // If a binding has not been specified, revert to incrementing resource indices
1189 switch (basetype)
1190 {
1191 case SPIRType::Struct:
1192 return next_metal_resource_index.msl_buffer++;
1193 case SPIRType::Image:
1194 return next_metal_resource_index.msl_texture++;
1195 case SPIRType::Sampler:
1196 return next_metal_resource_index.msl_sampler++;
1197 default:
1198 return 0;
1199 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001200}
1201
1202// Returns the name of the entry point of this shader
1203string CompilerMSL::get_entry_point_name()
1204{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +02001205 return clean_func_name(to_name(entry_point));
Bill Hollings103aabf2016-04-06 17:42:27 -04001206}
1207
1208// Returns the name of either the vertex index or instance index builtin
1209string CompilerMSL::get_vtx_idx_var_name(bool per_instance)
1210{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001211 BuiltIn builtin;
1212 uint32_t var_id;
Bill Hollings103aabf2016-04-06 17:42:27 -04001213
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001214 // Try modern builtin name first
1215 builtin = per_instance ? BuiltInInstanceIndex : BuiltInVertexIndex;
1216 var_id = builtin_vars[builtin];
1217 if (var_id)
1218 return to_expression(var_id);
Bill Hollings103aabf2016-04-06 17:42:27 -04001219
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001220 // Try legacy builtin name second
1221 builtin = per_instance ? BuiltInInstanceId : BuiltInVertexId;
1222 var_id = builtin_vars[builtin];
1223 if (var_id)
1224 return to_expression(var_id);
Bill Hollings103aabf2016-04-06 17:42:27 -04001225
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001226 return "missing_vtx_idx_var";
Bill Hollings103aabf2016-04-06 17:42:27 -04001227}
1228
Bill Hollings103aabf2016-04-06 17:42:27 -04001229// If the struct is packed, and the offset is greater than the current size of the struct,
1230// appends a padding member to the struct, and returns the offset to use for the next member,
1231// which is the offset provided. If the struct is not packed, or the offset is not greater
1232// than the struct size, no padding is added, and the struct size is returned.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001233uint32_t CompilerMSL::pad_to_offset(SPIRType &struct_type, uint32_t offset, uint32_t struct_size)
1234{
1235 if (!(struct_type.is_packed && offset > struct_size))
1236 return struct_size;
Bill Hollings103aabf2016-04-06 17:42:27 -04001237
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001238 auto &pad_type = get_pad_type(offset - struct_size);
1239 uint32_t mbr_idx = (uint32_t)struct_type.member_types.size();
1240 struct_type.member_types.push_back(pad_type.self);
1241 set_member_name(struct_type.self, mbr_idx, ("pad" + convert_to_string(mbr_idx)));
1242 set_member_decoration(struct_type.self, mbr_idx, DecorationOffset, struct_size);
1243 return offset;
Bill Hollings103aabf2016-04-06 17:42:27 -04001244}
1245
1246// Returns a char array type suitable for use as a padding member in a packed struct
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001247SPIRType &CompilerMSL::get_pad_type(uint32_t pad_len)
Bill Hollings103aabf2016-04-06 17:42:27 -04001248{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001249 uint32_t pad_type_id = pad_type_ids_by_pad_len[pad_len];
1250 if (pad_type_id != 0)
1251 return get<SPIRType>(pad_type_id);
Bill Hollings103aabf2016-04-06 17:42:27 -04001252
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001253 pad_type_id = increase_bound_by(1);
1254 auto &ib_type = set<SPIRType>(pad_type_id);
1255 ib_type.storage = StorageClassGeneric;
1256 ib_type.basetype = SPIRType::Char;
1257 ib_type.width = 8;
1258 ib_type.array.push_back(pad_len);
1259 set_decoration(ib_type.self, DecorationArrayStride, pad_len);
Bill Hollings103aabf2016-04-06 17:42:27 -04001260
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001261 pad_type_ids_by_pad_len[pad_len] = pad_type_id;
1262 return ib_type;
Bill Hollings103aabf2016-04-06 17:42:27 -04001263}
1264
1265string CompilerMSL::argument_decl(const SPIRFunction::Parameter &arg)
1266{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001267 auto &type = expression_type(arg.id);
1268 bool constref = !type.pointer || arg.write_count == 0;
Bill Hollings103aabf2016-04-06 17:42:27 -04001269
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001270 auto &var = get<SPIRVariable>(arg.id);
1271 return join(constref ? "const " : "", type_to_glsl(type), "& ", to_name(var.self), type_to_array_glsl(type));
Bill Hollings103aabf2016-04-06 17:42:27 -04001272}
1273
1274// Returns an MSL string describing the SPIR-V type
1275string CompilerMSL::type_to_glsl(const SPIRType &type)
1276{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001277 // Ignore the pointer type since GLSL doesn't have pointers.
Bill Hollings103aabf2016-04-06 17:42:27 -04001278
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001279 switch (type.basetype)
1280 {
1281 case SPIRType::Struct:
1282 // Need OpName lookup here to get a "sensible" name for a struct.
1283 return to_name(type.self);
Bill Hollings103aabf2016-04-06 17:42:27 -04001284
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001285 case SPIRType::Image:
1286 case SPIRType::SampledImage:
1287 return image_type_glsl(type);
Bill Hollings103aabf2016-04-06 17:42:27 -04001288
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001289 case SPIRType::Sampler:
1290 // Not really used.
1291 return "sampler";
Bill Hollings103aabf2016-04-06 17:42:27 -04001292
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001293 case SPIRType::Void:
1294 return "void";
Bill Hollings103aabf2016-04-06 17:42:27 -04001295
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001296 default:
1297 break;
1298 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001299
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001300 if (is_scalar(type)) // Scalar builtin
1301 {
1302 switch (type.basetype)
1303 {
Hans-Kristian Arntzen5f629272016-06-05 20:13:45 +02001304 case SPIRType::Boolean:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001305 return "bool";
1306 case SPIRType::Char:
1307 return "char";
1308 case SPIRType::Int:
1309 return (type.width == 16 ? "short" : "int");
1310 case SPIRType::UInt:
1311 return (type.width == 16 ? "ushort" : "uint");
1312 case SPIRType::AtomicCounter:
1313 return "atomic_uint";
1314 case SPIRType::Float:
1315 return (type.width == 16 ? "half" : "float");
1316 default:
1317 return "unknown_type";
1318 }
1319 }
1320 else if (is_vector(type)) // Vector builtin
1321 {
1322 switch (type.basetype)
1323 {
Hans-Kristian Arntzen5f629272016-06-05 20:13:45 +02001324 case SPIRType::Boolean:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001325 return join("bool", type.vecsize);
1326 case SPIRType::Char:
1327 return join("char", type.vecsize);
1328 ;
1329 case SPIRType::Int:
1330 return join((type.width == 16 ? "short" : "int"), type.vecsize);
1331 case SPIRType::UInt:
1332 return join((type.width == 16 ? "ushort" : "uint"), type.vecsize);
1333 case SPIRType::Float:
1334 return join((type.width == 16 ? "half" : "float"), type.vecsize);
1335 default:
1336 return "unknown_type";
1337 }
1338 }
1339 else
1340 {
1341 switch (type.basetype)
1342 {
Hans-Kristian Arntzen5f629272016-06-05 20:13:45 +02001343 case SPIRType::Boolean:
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001344 case SPIRType::Int:
1345 case SPIRType::UInt:
1346 case SPIRType::Float:
1347 return join((type.width == 16 ? "half" : "float"), type.columns, "x", type.vecsize);
1348 default:
1349 return "unknown_type";
1350 }
1351 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001352}
1353
1354// Returns an MSL string describing the SPIR-V image type
1355string CompilerMSL::image_type_glsl(const SPIRType &type)
1356{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001357 string img_type_name;
Bill Hollings1dbd18d2016-04-21 20:47:57 -04001358
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001359 auto &img_type = type.image;
1360 if (img_type.depth)
1361 {
1362 switch (img_type.dim)
1363 {
1364 case spv::Dim2D:
1365 img_type_name += (img_type.ms ? "depth2d_ms" : (img_type.arrayed ? "depth2d_array" : "depth2d"));
1366 break;
1367 case spv::DimCube:
1368 img_type_name += (img_type.arrayed ? "depthcube_array" : "depthcube");
1369 break;
1370 default:
1371 img_type_name += "unknown_depth_texture_type";
1372 break;
1373 }
1374 }
1375 else
1376 {
1377 switch (img_type.dim)
1378 {
1379 case spv::Dim1D:
1380 img_type_name += (img_type.arrayed ? "texture1d_array" : "texture1d");
1381 break;
1382 case spv::DimBuffer:
1383 case spv::Dim2D:
1384 img_type_name += (img_type.ms ? "texture2d_ms" : (img_type.arrayed ? "texture2d_array" : "texture2d"));
1385 break;
1386 case spv::Dim3D:
1387 img_type_name += "texture3D";
1388 break;
1389 case spv::DimCube:
1390 img_type_name += (img_type.arrayed ? "texturecube_array" : "texturecube");
1391 break;
1392 default:
1393 img_type_name += "unknown_texture_type";
1394 break;
1395 }
1396 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001397
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001398 // Append the pixel type
1399 auto &img_pix_type = get<SPIRType>(img_type.type);
1400 img_type_name += "<" + type_to_glsl(img_pix_type) + ">";
Bill Hollings1dbd18d2016-04-21 20:47:57 -04001401
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001402 return img_type_name;
Bill Hollings103aabf2016-04-06 17:42:27 -04001403}
1404
1405// Returns an MSL string identifying the name of a SPIR-V builtin
1406string CompilerMSL::builtin_to_glsl(BuiltIn builtin)
1407{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001408 switch (builtin)
1409 {
1410 case BuiltInPosition:
1411 return (stage_out_var_name + ".gl_Position");
1412 case BuiltInPointSize:
1413 return (stage_out_var_name + ".gl_PointSize");
1414 case BuiltInVertexId:
1415 return "gl_VertexID";
1416 case BuiltInInstanceId:
1417 return "gl_InstanceID";
1418 case BuiltInVertexIndex:
1419 return "gl_VertexIndex";
1420 case BuiltInInstanceIndex:
1421 return "gl_InstanceIndex";
1422 case BuiltInPrimitiveId:
1423 return "gl_PrimitiveID";
1424 case BuiltInInvocationId:
1425 return "gl_InvocationID";
1426 case BuiltInLayer:
1427 return "gl_Layer";
1428 case BuiltInTessLevelOuter:
1429 return "gl_TessLevelOuter";
1430 case BuiltInTessLevelInner:
1431 return "gl_TessLevelInner";
1432 case BuiltInTessCoord:
1433 return "gl_TessCoord";
1434 case BuiltInFragCoord:
1435 return "gl_FragCoord";
1436 case BuiltInPointCoord:
1437 return "gl_PointCoord";
1438 case BuiltInFrontFacing:
1439 return "gl_FrontFacing";
1440 case BuiltInFragDepth:
1441 return "gl_FragDepth";
1442 case BuiltInNumWorkgroups:
1443 return "gl_NumWorkGroups";
1444 case BuiltInWorkgroupSize:
1445 return "gl_WorkGroupSize";
1446 case BuiltInWorkgroupId:
1447 return "gl_WorkGroupID";
1448 case BuiltInLocalInvocationId:
1449 return "gl_LocalInvocationID";
1450 case BuiltInGlobalInvocationId:
1451 return "gl_GlobalInvocationID";
1452 case BuiltInLocalInvocationIndex:
1453 return "gl_LocalInvocationIndex";
1454 default:
1455 return "gl_???";
1456 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001457}
1458
1459// Returns an MSL string attribute qualifer for a SPIR-V builtin
1460string CompilerMSL::builtin_qualifier(BuiltIn builtin)
1461{
Hans-Kristian Arntzen042475e2016-07-28 11:16:02 +02001462 auto &execution = get_entry_point();
1463
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001464 switch (builtin)
1465 {
1466 // Vertex function in
1467 case BuiltInVertexId:
1468 return "vertex_id";
1469 case BuiltInVertexIndex:
1470 return "vertex_id";
1471 case BuiltInInstanceId:
1472 return "instance_id";
1473 case BuiltInInstanceIndex:
1474 return "instance_id";
Bill Hollings103aabf2016-04-06 17:42:27 -04001475
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001476 // Vertex function out
1477 case BuiltInClipDistance:
1478 return "clip_distance";
1479 case BuiltInPointSize:
1480 return "point_size";
1481 case BuiltInPosition:
1482 return "position";
1483 case BuiltInLayer:
1484 return "render_target_array_index";
Bill Hollings103aabf2016-04-06 17:42:27 -04001485
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001486 // Fragment function in
1487 case BuiltInFrontFacing:
1488 return "front_facing";
1489 case BuiltInPointCoord:
1490 return "point_coord";
1491 case BuiltInSamplePosition:
1492 return "position";
1493 case BuiltInSampleId:
1494 return "sample_id";
1495 case BuiltInSampleMask:
1496 return "sample_mask";
Bill Hollings103aabf2016-04-06 17:42:27 -04001497
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001498 // Fragment function out
1499 case BuiltInFragDepth:
1500 {
1501 if (execution.flags & (1ull << ExecutionModeDepthGreater))
1502 return "depth(greater)";
Bill Hollings103aabf2016-04-06 17:42:27 -04001503
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001504 if (execution.flags & (1ull << ExecutionModeDepthLess))
1505 return "depth(less)";
Bill Hollings103aabf2016-04-06 17:42:27 -04001506
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001507 if (execution.flags & (1ull << ExecutionModeDepthUnchanged))
1508 return "depth(any)";
1509 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001510
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001511 default:
1512 return "unsupported-built-in";
1513 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001514}
1515
1516// Returns an MSL string type declaration for a SPIR-V builtin
1517string CompilerMSL::builtin_type_decl(BuiltIn builtin)
1518{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001519 switch (builtin)
1520 {
1521 // Vertex function in
1522 case BuiltInVertexId:
1523 return "uint";
1524 case BuiltInVertexIndex:
1525 return "uint";
1526 case BuiltInInstanceId:
1527 return "uint";
1528 case BuiltInInstanceIndex:
1529 return "uint";
Bill Hollings103aabf2016-04-06 17:42:27 -04001530
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001531 // Vertex function out
1532 case BuiltInClipDistance:
1533 return "float";
1534 case BuiltInPointSize:
1535 return "float";
1536 case BuiltInPosition:
1537 return "float4";
Bill Hollings103aabf2016-04-06 17:42:27 -04001538
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001539 // Fragment function in
1540 case BuiltInFrontFacing:
1541 return "bool";
1542 case BuiltInPointCoord:
1543 return "float2";
1544 case BuiltInSamplePosition:
1545 return "float4";
1546 case BuiltInSampleId:
1547 return "uint";
1548 case BuiltInSampleMask:
1549 return "uint";
Bill Hollings103aabf2016-04-06 17:42:27 -04001550
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001551 default:
1552 return "unsupported-built-in-type";
1553 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001554}
1555
1556// Returns the effective size of a buffer block struct member.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001557size_t CompilerMSL::get_declared_struct_member_size(const SPIRType &struct_type, uint32_t index) const
Bill Hollings103aabf2016-04-06 17:42:27 -04001558{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001559 auto &type = get<SPIRType>(struct_type.member_types[index]);
1560 auto dec_mask = get_member_decoration_mask(struct_type.self, index);
1561 return get_declared_type_size(type, dec_mask);
Bill Hollings103aabf2016-04-06 17:42:27 -04001562}
1563
1564// Returns the effective size of a variable type.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001565size_t CompilerMSL::get_declared_type_size(const SPIRType &type) const
Bill Hollings103aabf2016-04-06 17:42:27 -04001566{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001567 return get_declared_type_size(type, get_decoration_mask(type.self));
Bill Hollings103aabf2016-04-06 17:42:27 -04001568}
1569
1570// Returns the effective size of a variable type or member type,
1571// taking into consideration the specified mask of decorations.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001572size_t CompilerMSL::get_declared_type_size(const SPIRType &type, uint64_t dec_mask) const
Bill Hollings103aabf2016-04-06 17:42:27 -04001573{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001574 if (type.basetype != SPIRType::Struct)
1575 {
1576 switch (type.basetype)
1577 {
1578 case SPIRType::Unknown:
1579 case SPIRType::Void:
1580 case SPIRType::AtomicCounter:
1581 case SPIRType::Image:
1582 case SPIRType::SampledImage:
1583 case SPIRType::Sampler:
1584 throw CompilerError("Querying size of object with opaque size.");
1585 default:
1586 break;
1587 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001588
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001589 size_t component_size = type.width / 8;
1590 unsigned vecsize = type.vecsize;
1591 unsigned columns = type.columns;
Bill Hollings103aabf2016-04-06 17:42:27 -04001592
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001593 if (type.array.empty())
1594 {
1595 // Vectors.
1596 if (columns == 1)
1597 return vecsize * component_size;
1598 else
1599 {
1600 // Per SPIR-V spec, matrices must be tightly packed and aligned up for vec3 accesses.
1601 if ((dec_mask & (1ull << DecorationRowMajor)) && columns == 3)
1602 columns = 4;
1603 else if ((dec_mask & (1ull << DecorationColMajor)) && vecsize == 3)
1604 vecsize = 4;
Bill Hollings103aabf2016-04-06 17:42:27 -04001605
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001606 return vecsize * columns * component_size;
1607 }
1608 }
1609 else
1610 {
1611 // For arrays, we can use ArrayStride to get an easy check.
1612 // ArrayStride is part of the array type not OpMemberDecorate.
1613 auto &dec = meta[type.self].decoration;
1614 if (dec.decoration_flags & (1ull << DecorationArrayStride))
1615 return dec.array_stride * type.array.back();
1616 else
1617 throw CompilerError("Type does not have ArrayStride set.");
1618 }
1619 }
1620 else
1621 {
1622 // Recurse.
1623 uint32_t last = uint32_t(type.member_types.size() - 1);
1624 uint32_t offset = type_struct_member_offset(type, last);
1625 size_t size = get_declared_struct_size(get<SPIRType>(type.member_types.back()));
1626 return offset + size;
1627 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001628}
1629
1630// Sort both type and meta member content based on builtin status (put builtins at end), then by location.
1631void MemberSorterByLocation::sort()
1632{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001633 // Create a temporary array of consecutive member indices and sort it base on
1634 // how the members should be reordered, based on builtin and location meta info.
1635 size_t mbr_cnt = type.member_types.size();
1636 vector<uint32_t> mbr_idxs(mbr_cnt);
1637 iota(mbr_idxs.begin(), mbr_idxs.end(), 0); // Fill with consecutive indices
1638 std::sort(mbr_idxs.begin(), mbr_idxs.end(), *this); // Sort member indices based on member locations
Bill Hollings103aabf2016-04-06 17:42:27 -04001639
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001640 // Move type and meta member info to the order defined by the sorted member indices.
1641 // This is done by creating temporary copies of both member types and meta, and then
1642 // copying back to the original content at the sorted indices.
1643 auto mbr_types_cpy = type.member_types;
1644 auto mbr_meta_cpy = meta.members;
1645 for (uint32_t mbr_idx = 0; mbr_idx < mbr_cnt; mbr_idx++)
1646 {
1647 type.member_types[mbr_idx] = mbr_types_cpy[mbr_idxs[mbr_idx]];
1648 meta.members[mbr_idx] = mbr_meta_cpy[mbr_idxs[mbr_idx]];
1649 }
Bill Hollings103aabf2016-04-06 17:42:27 -04001650}
1651
1652// Sort first by builtin status (put builtins at end), then by location.
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001653bool MemberSorterByLocation::operator()(uint32_t mbr_idx1, uint32_t mbr_idx2)
Bill Hollings103aabf2016-04-06 17:42:27 -04001654{
Hans-Kristian Arntzen4b8ed532016-05-05 09:33:18 +02001655 auto &mbr_meta1 = meta.members[mbr_idx1];
1656 auto &mbr_meta2 = meta.members[mbr_idx2];
1657 if (mbr_meta1.builtin != mbr_meta2.builtin)
1658 return mbr_meta2.builtin;
1659 else
1660 return mbr_meta1.location < mbr_meta2.location;
Bill Hollings103aabf2016-04-06 17:42:27 -04001661}