]> git.tdb.fi Git - libs/gl.git/blob - source/glsl/spirv.cpp
40e731fe63fa9fcfb384dd61baf8429e34be3382
[libs/gl.git] / source / glsl / spirv.cpp
1 #include <msp/core/algorithm.h>
2 #include <msp/core/maputils.h>
3 #include <msp/core/raii.h>
4 #include "reflect.h"
5 #include "spirv.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GL {
11 namespace SL {
12
13 const SpirVGenerator::BuiltinFunctionInfo SpirVGenerator::builtin_functions[] =
14 {
15         { "radians", "f", "GLSL.std.450", GLSL450_RADIANS, { 1 }, 0, 0 },
16         { "degrees", "f", "GLSL.std.450", GLSL450_DEGREES, { 1 }, 0, 0 },
17         { "sin", "f", "GLSL.std.450", GLSL450_SIN, { 1 }, 0, 0 },
18         { "cos", "f", "GLSL.std.450", GLSL450_COS, { 1 }, 0, 0 },
19         { "tan", "f", "GLSL.std.450", GLSL450_TAN, { 1 }, 0, 0 },
20         { "asin", "f", "GLSL.std.450", GLSL450_ASIN, { 1 }, 0, 0 },
21         { "acos", "f", "GLSL.std.450", GLSL450_ACOS, { 1 }, 0, 0 },
22         { "atan", "f", "GLSL.std.450", GLSL450_ATAN, { 1 }, 0, 0 },
23         { "atan", "ff", "GLSL.std.450", GLSL450_ATAN2, { 1, 2 }, 0, 0 },
24         { "sinh", "f", "GLSL.std.450", GLSL450_SINH, { 1 }, 0, 0 },
25         { "cosh", "f", "GLSL.std.450", GLSL450_COSH, { 1 }, 0, 0 },
26         { "tanh", "f", "GLSL.std.450", GLSL450_TANH, { 1 }, 0, 0 },
27         { "asinh", "f", "GLSL.std.450", GLSL450_ASINH, { 1 }, 0, 0 },
28         { "acosh", "f", "GLSL.std.450", GLSL450_ACOSH, { 1 }, 0, 0 },
29         { "atanh", "f", "GLSL.std.450", GLSL450_ATANH, { 1 }, 0, 0 },
30         { "pow", "ff", "GLSL.std.450", GLSL450_POW, { 1, 2 }, 0, 0 },
31         { "exp", "f", "GLSL.std.450", GLSL450_EXP, { 1 }, 0, 0 },
32         { "log", "f", "GLSL.std.450", GLSL450_LOG, { 1 }, 0, 0 },
33         { "exp2", "f", "GLSL.std.450", GLSL450_EXP2, { 1 }, 0, 0 },
34         { "log2", "f", "GLSL.std.450", GLSL450_LOG2, { 1 }, 0, 0 },
35         { "sqrt", "f", "GLSL.std.450", GLSL450_SQRT, { 1 }, 0, 0 },
36         { "inversesqrt", "f", "GLSL.std.450", GLSL450_INVERSE_SQRT, { 1 }, 0, 0 },
37         { "abs", "f", "GLSL.std.450", GLSL450_F_ABS, { 1 }, 0, 0 },
38         { "abs", "i", "GLSL.std.450", GLSL450_S_ABS, { 1 }, 0, 0 },
39         { "sign", "f", "GLSL.std.450", GLSL450_F_SIGN, { 1 }, 0, 0 },
40         { "sign", "i", "GLSL.std.450", GLSL450_S_SIGN, { 1 }, 0, 0 },
41         { "floor", "f", "GLSL.std.450", GLSL450_FLOOR, { 1 }, 0, 0 },
42         { "trunc", "f", "GLSL.std.450", GLSL450_TRUNC, { 1 }, 0, 0 },
43         { "round", "f", "GLSL.std.450", GLSL450_ROUND, { 1 }, 0, 0 },
44         { "roundEven", "f", "GLSL.std.450", GLSL450_ROUND_EVEN, { 1 }, 0, 0 },
45         { "ceil", "f", "GLSL.std.450", GLSL450_CEIL, { 1 }, 0, 0 },
46         { "fract", "f", "GLSL.std.450", GLSL450_FRACT, { 1 }, 0, 0 },
47         { "mod", "f", "", OP_F_MOD, { 1, 2 }, 0, 0 },
48         { "min", "ff", "GLSL.std.450", GLSL450_F_MIN, { 1, 2 }, 0, 0 },
49         { "min", "ii", "GLSL.std.450", GLSL450_S_MIN, { 1, 2 }, 0, 0 },
50         { "min", "uu", "GLSL.std.450", GLSL450_U_MIN, { 1, 2 }, 0, 0 },
51         { "max", "ff", "GLSL.std.450", GLSL450_F_MAX, { 1, 2 }, 0, 0 },
52         { "max", "ii", "GLSL.std.450", GLSL450_S_MAX, { 1, 2 }, 0, 0 },
53         { "max", "uu", "GLSL.std.450", GLSL450_U_MAX, { 1, 2 }, 0, 0 },
54         { "clamp", "fff", "GLSL.std.450", GLSL450_F_CLAMP, { 1, 2, 3 }, 0, 0 },
55         { "clamp", "iii", "GLSL.std.450", GLSL450_S_CLAMP, { 1, 2, 3 }, 0, 0 },
56         { "clamp", "uuu", "GLSL.std.450", GLSL450_U_CLAMP, { 1, 2, 3 }, 0, 0 },
57         { "mix", "fff", "GLSL.std.450", GLSL450_F_MIX, { 1, 2, 3 }, 0, 0 },
58         { "mix", "ffb", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
59         { "mix", "iib", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
60         { "mix", "uub", "", OP_SELECT, { 3, 2, 1 }, 0, 0 },
61         { "step", "ff", "GLSL.std.450", GLSL450_F_STEP, { 1, 2 }, 0, 0 },
62         { "smoothstep", "fff", "GLSL.std.450", GLSL450_F_SMOOTH_STEP, { 1, 2, 3 }, 0, 0 },
63         { "isnan", "f", "", OP_IS_NAN, { 1 }, 0, 0 },
64         { "isinf", "f", "", OP_IS_INF, { 1 }, 0, 0 },
65         { "fma", "fff", "GLSL.std.450", GLSL450_F_FMA, { 1, 2, 3 }, 0, 0 },
66         { "length", "f", "GLSL.std.450", GLSL450_LENGTH, { 1 }, 0, 0 },
67         { "distance", "ff", "GLSL.std.450", GLSL450_DISTANCE, { 1, 2 }, 0, 0 },
68         { "dot", "ff", "", OP_DOT, { 1, 2 }, 0, 0 },
69         { "cross", "ff", "GLSL.std.450", GLSL450_CROSS, { 1, 2 }, 0, 0 },
70         { "normalize", "f", "GLSL.std.450", GLSL450_NORMALIZE, { 1 }, 0, 0 },
71         { "faceforward", "fff", "GLSL.std.450", GLSL450_FACE_FORWARD, { 1, 2, 3 }, 0, 0 },
72         { "reflect", "ff", "GLSL.std.450", GLSL450_REFLECT, { 1, 2 }, 0, 0 },
73         { "refract", "fff", "GLSL.std.450", GLSL450_REFRACT, { 1, 2, 3 }, 0, 0 },
74         { "matrixCompMult", "ff", "", 0, { 0 }, 0, &SpirVGenerator::visit_builtin_matrix_comp_mult },
75         { "outerProduct", "ff", "", OP_OUTER_PRODUCT, { 1, 2 }, 0, 0 },
76         { "transpose", "f", "", OP_TRANSPOSE, { 1 }, 0, 0 },
77         { "determinant", "f", "GLSL.std.450", GLSL450_DETERMINANT, { 1 }, 0, 0 },
78         { "inverse", "f", "GLSL.std.450", GLSL450_MATRIX_INVERSE, { 1 }, 0, 0 },
79         { "lessThan", "ff", "", OP_F_ORD_LESS_THAN, { 1, 2 }, 0, 0 },
80         { "lessThan", "ii", "", OP_S_LESS_THAN, { 1, 2 }, 0, 0 },
81         { "lessThan", "uu", "", OP_U_LESS_THAN, { 1, 2 }, 0, 0 },
82         { "lessThanEqual", "ff", "", OP_F_ORD_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
83         { "lessThanEqual", "ii", "", OP_S_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
84         { "lessThanEqual", "uu", "", OP_U_LESS_THAN_EQUAL, { 1, 2 }, 0, 0 },
85         { "greaterThan", "ff", "", OP_F_ORD_GREATER_THAN, { 1, 2 }, 0, 0 },
86         { "greaterThan", "ii", "", OP_S_GREATER_THAN, { 1, 2 }, 0, 0 },
87         { "greaterThan", "uu", "", OP_U_GREATER_THAN, { 1, 2 }, 0, 0 },
88         { "greaterThanEqual", "ff", "", OP_F_ORD_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
89         { "greaterThanEqual", "ii", "", OP_S_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
90         { "greaterThanEqual", "uu", "", OP_U_GREATER_THAN_EQUAL, { 1, 2 }, 0, 0 },
91         { "equal", "ff", "", OP_F_ORD_EQUAL, { 1, 2 }, 0, 0 },
92         { "equal", "ii", "", OP_I_EQUAL, { 1, 2 }, 0, 0 },
93         { "equal", "uu", "", OP_I_EQUAL, { 1, 2 }, 0, 0 },
94         { "notEqual", "ff", "", OP_F_ORD_NOT_EQUAL, { 1, 2 }, 0, 0 },
95         { "notEqual", "ii", "", OP_I_NOT_EQUAL, { 1, 2 }, 0, 0 },
96         { "notEqual", "uu", "", OP_I_NOT_EQUAL, { 1, 2 }, 0, 0 },
97         { "any", "b", "", OP_ANY, { 1 }, 0, 0 },
98         { "all", "b", "", OP_ALL, { 1 }, 0, 0 },
99         { "not", "b", "", OP_LOGICAL_NOT, { 1 }, 0, 0 },
100         { "bitfieldExtract", "iii", "", OP_BIT_FIELD_S_EXTRACT, { 1, 2, 3 }, 0, 0 },
101         { "bitfieldExtract", "uii", "", OP_BIT_FIELD_U_EXTRACT, { 1, 2, 3 }, 0, 0 },
102         { "bitfieldInsert", "iiii", "", OP_BIT_FIELD_INSERT, { 1, 2, 3, 4 }, 0, 0 },
103         { "bitfieldInsert", "uuii", "", OP_BIT_FIELD_INSERT, { 1, 2, 3, 4 }, 0, 0 },
104         { "bitfieldReverse", "i", "", OP_BIT_REVERSE, { 1 }, 0, 0 },
105         { "bitfieldReverse", "u", "", OP_BIT_REVERSE, { 1 }, 0, 0 },
106         { "bitCount", "i", "", OP_BIT_COUNT, { 1 }, 0, 0 },
107         { "findLSB", "i", "GLSL.std.450", GLSL450_FIND_I_LSB, { 1 }, 0, 0 },
108         { "findLSB", "u", "GLSL.std.450", GLSL450_FIND_I_LSB, { 1 }, 0, 0 },
109         { "findMSB", "i", "GLSL.std.450", GLSL450_FIND_S_MSB, { 1 }, 0, 0 },
110         { "findMSB", "u", "GLSL.std.450", GLSL450_FIND_U_MSB, { 1 }, 0, 0 },
111         { "textureSize", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
112         { "textureQueryLod", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
113         { "textureQueryLevels", "", "", 0, { }, CAP_IMAGE_QUERY, &SpirVGenerator::visit_builtin_texture_query },
114         { "texture", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texture },
115         { "textureLod", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texture },
116         { "texelFetch", "", "", 0, { }, 0, &SpirVGenerator::visit_builtin_texel_fetch },
117         { "EmitVertex", "", "", OP_EMIT_VERTEX, { }, 0, 0 },
118         { "EndPrimitive", "", "", OP_END_PRIMITIVE, { }, 0, 0 },
119         { "dFdx", "f", "", OP_DP_DX, { 1 }, 0, 0 },
120         { "dFdy", "f", "", OP_DP_DY, { 1 }, 0, 0 },
121         { "dFdxFine", "f", "", OP_DP_DX_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
122         { "dFdyFine", "f", "", OP_DP_DY_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
123         { "dFdxCoarse", "f", "", OP_DP_DX_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
124         { "dFdyCoarse", "f", "", OP_DP_DY_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
125         { "fwidth", "f", "", OP_FWIDTH, { 1 }, 0, 0 },
126         { "fwidthFine", "f", "", OP_FWIDTH_FINE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
127         { "fwidthCoarse", "f", "", OP_FWIDTH_COARSE, { 1 }, CAP_DERIVATIVE_CONTROL, 0 },
128         { "interpolateAtCentroid", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
129         { "interpolateAtSample", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
130         { "interpolateAtOffset", "", "", 0, { }, CAP_INTERPOLATION_FUNCTION, &SpirVGenerator::visit_builtin_interpolate },
131         { "", "", "", 0, { }, 0, 0 }
132 };
133
134 SpirVGenerator::SpirVGenerator():
135         writer(content)
136 { }
137
138 void SpirVGenerator::apply(Module &module)
139 {
140         use_capability(CAP_SHADER);
141
142         for(Stage &s: module.stages)
143         {
144                 stage = &s;
145                 interface_layouts.clear();
146                 s.content.visit(*this);
147         }
148
149         writer.finalize(SPIRV_GENERATOR_MSP, next_id);
150 }
151
152 SpirVGenerator::StorageClass SpirVGenerator::get_interface_storage(const string &iface, bool block)
153 {
154         if(iface=="in")
155                 return STORAGE_INPUT;
156         else if(iface=="out")
157                 return STORAGE_OUTPUT;
158         else if(iface=="uniform")
159                 return (block ? STORAGE_UNIFORM : STORAGE_UNIFORM_CONSTANT);
160         else if(iface.empty())
161                 return STORAGE_PRIVATE;
162         else
163                 throw invalid_argument("SpirVGenerator::get_interface_storage");
164 }
165
166 SpirVGenerator::BuiltinSemantic SpirVGenerator::get_builtin_semantic(const string &name)
167 {
168         if(name=="gl_Position")
169                 return BUILTIN_POSITION;
170         else if(name=="gl_PointSize")
171                 return BUILTIN_POINT_SIZE;
172         else if(name=="gl_ClipDistance")
173                 return BUILTIN_CLIP_DISTANCE;
174         else if(name=="gl_VertexID")
175                 return BUILTIN_VERTEX_ID;
176         else if(name=="gl_InstanceID")
177                 return BUILTIN_INSTANCE_ID;
178         else if(name=="gl_PrimitiveID" || name=="gl_PrimitiveIDIn")
179                 return BUILTIN_PRIMITIVE_ID;
180         else if(name=="gl_InvocationID")
181                 return BUILTIN_INVOCATION_ID;
182         else if(name=="gl_Layer")
183                 return BUILTIN_LAYER;
184         else if(name=="gl_FragCoord")
185                 return BUILTIN_FRAG_COORD;
186         else if(name=="gl_PointCoord")
187                 return BUILTIN_POINT_COORD;
188         else if(name=="gl_FrontFacing")
189                 return BUILTIN_FRONT_FACING;
190         else if(name=="gl_SampleId")
191                 return BUILTIN_SAMPLE_ID;
192         else if(name=="gl_SamplePosition")
193                 return BUILTIN_SAMPLE_POSITION;
194         else if(name=="gl_FragDepth")
195                 return BUILTIN_FRAG_DEPTH;
196         else
197                 throw invalid_argument("SpirVGenerator::get_builtin_semantic");
198 }
199
200 void SpirVGenerator::use_capability(Capability cap)
201 {
202         if(used_capabilities.count(cap))
203                 return;
204
205         used_capabilities.insert(cap);
206         writer.write_op(content.capabilities, OP_CAPABILITY, cap);
207 }
208
209 SpirVGenerator::Id SpirVGenerator::import_extension(const string &name)
210 {
211         Id &ext_id = imported_extension_ids[name];
212         if(!ext_id)
213         {
214                 ext_id = next_id++;
215                 writer.begin_op(content.extensions, OP_EXT_INST_IMPORT);
216                 writer.write(ext_id);
217                 writer.write_string(name);
218                 writer.end_op(OP_EXT_INST_IMPORT);
219         }
220         return ext_id;
221 }
222
223 SpirVGenerator::Id SpirVGenerator::get_id(Node &node) const
224 {
225         return get_item(declared_ids, &node).id;
226 }
227
228 SpirVGenerator::Id SpirVGenerator::allocate_id(Node &node, Id type_id)
229 {
230         auto i = declared_ids.find(&node);
231         if(i!=declared_ids.end())
232         {
233                 if(i->second.type_id)
234                         throw key_error(&node);
235                 i->second.type_id = type_id;
236                 return i->second.id;
237         }
238
239         Id id = next_id++;
240         declared_ids.insert(make_pair(&node, Declaration(id, type_id)));
241         return id;
242 }
243
244 SpirVGenerator::Id SpirVGenerator::allocate_forward_id(Node &node)
245 {
246         auto i = declared_ids.find(&node);
247         if(i!=declared_ids.end())
248                 return i->second.id;
249
250         Id id = next_id++;
251         declared_ids.insert(make_pair(&node, Declaration(id, 0)));
252         return id;
253 }
254
255 SpirVGenerator::Id SpirVGenerator::write_constant(Id type_id, Word value, bool spec)
256 {
257         Id const_id = next_id++;
258         if(is_scalar_type(type_id, BasicTypeDeclaration::BOOL))
259         {
260                 Opcode opcode = (value ? (spec ? OP_SPEC_CONSTANT_TRUE : OP_CONSTANT_TRUE) :
261                         (spec ? OP_SPEC_CONSTANT_FALSE : OP_CONSTANT_FALSE));
262                 writer.write_op(content.globals, opcode, type_id, const_id);
263         }
264         else
265         {
266                 Opcode opcode = (spec ? OP_SPEC_CONSTANT : OP_CONSTANT);
267                 writer.write_op(content.globals, opcode, type_id, const_id, value);
268         }
269         return const_id;
270 }
271
272 SpirVGenerator::ConstantKey SpirVGenerator::get_constant_key(Id type_id, const Variant &value)
273 {
274         if(value.check_type<bool>())
275                 return ConstantKey(type_id, value.value<bool>());
276         else if(value.check_type<int>())
277                 return ConstantKey(type_id, value.value<int>());
278         else if(value.check_type<unsigned>())
279                 return ConstantKey(type_id, value.value<unsigned>());
280         else if(value.check_type<float>())
281                 return ConstantKey(type_id, value.value<float>());
282         else
283                 throw invalid_argument("SpirVGenerator::get_constant_key");
284 }
285
286 SpirVGenerator::Id SpirVGenerator::get_constant_id(Id type_id, const Variant &value)
287 {
288         ConstantKey key = get_constant_key(type_id, value);
289         Id &const_id = constant_ids[key];
290         if(!const_id)
291                 const_id = write_constant(type_id, key.int_value, false);
292         return const_id;
293 }
294
295 SpirVGenerator::Id SpirVGenerator::get_vector_constant_id(Id type_id, unsigned size, Id scalar_id)
296 {
297         Id &const_id = constant_ids[get_constant_key(type_id, static_cast<int>(scalar_id))];
298         if(!const_id)
299         {
300                 const_id = next_id++;
301                 writer.begin_op(content.globals, OP_CONSTANT_COMPOSITE, 3+size);
302                 writer.write(type_id);
303                 writer.write(const_id);
304                 for(unsigned i=0; i<size; ++i)
305                         writer.write(scalar_id);
306                 writer.end_op(OP_CONSTANT_COMPOSITE);
307         }
308         return const_id;
309 }
310
311 SpirVGenerator::Id SpirVGenerator::get_standard_type_id(BasicTypeDeclaration::Kind kind, unsigned size, bool sign)
312 {
313         Id base_id = (size>1 ? get_standard_type_id(kind, 1, sign) : 0);
314         Id &type_id = standard_type_ids[base_id ? TypeKey(base_id, size) : TypeKey(kind, sign)];
315         if(!type_id)
316         {
317                 type_id = next_id++;
318                 if(size>1)
319                         writer.write_op(content.globals, OP_TYPE_VECTOR, type_id, base_id, size);
320                 else if(kind==BasicTypeDeclaration::VOID)
321                         writer.write_op(content.globals, OP_TYPE_VOID, type_id);
322                 else if(kind==BasicTypeDeclaration::BOOL)
323                         writer.write_op(content.globals, OP_TYPE_BOOL, type_id);
324                 else if(kind==BasicTypeDeclaration::INT)
325                         writer.write_op(content.globals, OP_TYPE_INT, type_id, 32, sign);
326                 else if(kind==BasicTypeDeclaration::FLOAT)
327                         writer.write_op(content.globals, OP_TYPE_FLOAT, type_id, 32);
328                 else
329                         throw invalid_argument("SpirVGenerator::get_standard_type_id");
330         }
331         return type_id;
332 }
333
334 bool SpirVGenerator::is_scalar_type(Id type_id, BasicTypeDeclaration::Kind kind) const
335 {
336         auto i = standard_type_ids.find(TypeKey(kind, true));
337         return (i!=standard_type_ids.end() && i->second==type_id);
338 }
339
340 SpirVGenerator::Id SpirVGenerator::get_array_type_id(TypeDeclaration &base_type, Id size_id)
341 {
342         Id base_type_id = get_id(base_type);
343         Id &array_type_id = array_type_ids[TypeKey(base_type_id, size_id)];
344         if(!array_type_id)
345         {
346                 array_type_id = next_id++;
347                 if(size_id)
348                         writer.write_op(content.globals, OP_TYPE_ARRAY, array_type_id, base_type_id, size_id);
349                 else
350                         writer.write_op(content.globals, OP_TYPE_RUNTIME_ARRAY, array_type_id, base_type_id);
351
352                 unsigned stride = MemoryRequirementsCalculator().apply(base_type).stride;
353                 writer.write_op_decorate(array_type_id, DECO_ARRAY_STRIDE, stride);
354         }
355
356         return array_type_id;
357 }
358
359 SpirVGenerator::Id SpirVGenerator::get_pointer_type_id(Id type_id, StorageClass storage)
360 {
361         Id &ptr_type_id = pointer_type_ids[TypeKey(type_id, storage)];
362         if(!ptr_type_id)
363         {
364                 ptr_type_id = next_id++;
365                 writer.write_op(content.globals, OP_TYPE_POINTER, ptr_type_id, storage, type_id);
366         }
367         return ptr_type_id;
368 }
369
370 SpirVGenerator::Id SpirVGenerator::get_variable_type_id(const VariableDeclaration &var)
371 {
372         if(const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var.type_declaration))
373                 if(basic->kind==BasicTypeDeclaration::ARRAY)
374                 {
375                         Id size_id = 0;
376                         if(var.array_size)
377                         {
378                                 SetFlag set_const(constant_expression);
379                                 r_expression_result_id = 0;
380                                 var.array_size->visit(*this);
381                                 size_id = r_expression_result_id;
382                         }
383                         else
384                                 size_id = get_constant_id(get_standard_type_id(BasicTypeDeclaration::INT, 1), 1);
385                         return get_array_type_id(*basic->base_type, size_id);
386                 }
387
388         return get_id(*var.type_declaration);
389 }
390
391 SpirVGenerator::Id SpirVGenerator::get_load_id(VariableDeclaration &var)
392 {
393         Id &load_result_id = variable_load_ids[&var];
394         if(!load_result_id)
395         {
396                 load_result_id = next_id++;
397                 writer.write_op(content.function_body, OP_LOAD, get_variable_type_id(var), load_result_id, get_id(var));
398         }
399         return load_result_id;
400 }
401
402 void SpirVGenerator::prune_loads(Id min_id)
403 {
404         for(auto i=variable_load_ids.begin(); i!=variable_load_ids.end(); )
405         {
406                 if(i->second>=min_id)
407                         variable_load_ids.erase(i++);
408                 else
409                         ++i;
410         }
411 }
412
413 SpirVGenerator::Id SpirVGenerator::begin_expression(Opcode opcode, Id type_id, unsigned n_args)
414 {
415         bool has_result = (opcode==OP_FUNCTION_CALL || !is_scalar_type(type_id, BasicTypeDeclaration::VOID));
416         if(!constant_expression)
417         {
418                 if(!current_function)
419                         throw internal_error("non-constant expression outside a function");
420
421                 writer.begin_op(content.function_body, opcode, (n_args ? 1+has_result*2+n_args : 0));
422         }
423         else if(opcode==OP_COMPOSITE_CONSTRUCT)
424                 writer.begin_op(content.globals, (spec_constant ? OP_SPEC_CONSTANT_COMPOSITE : OP_CONSTANT_COMPOSITE),
425                         (n_args ? 1+has_result*2+n_args : 0));
426         else if(!spec_constant)
427                 throw internal_error("invalid non-specialization constant expression");
428         else
429                 writer.begin_op(content.globals, OP_SPEC_CONSTANT_OP, (n_args ? 2+has_result*2+n_args : 0));
430
431         Id result_id = next_id++;
432         if(has_result)
433         {
434                 writer.write(type_id);
435                 writer.write(result_id);
436         }
437         if(spec_constant && opcode!=OP_COMPOSITE_CONSTRUCT)
438                 writer.write(opcode);
439
440         return result_id;
441 }
442
443 void SpirVGenerator::end_expression(Opcode opcode)
444 {
445         if(constant_expression)
446                 opcode = (opcode==OP_COMPOSITE_CONSTRUCT ? spec_constant ? OP_SPEC_CONSTANT_COMPOSITE : OP_CONSTANT_COMPOSITE : OP_SPEC_CONSTANT_OP);
447         writer.end_op(opcode);
448 }
449
450 SpirVGenerator::Id SpirVGenerator::write_expression(Opcode opcode, Id type_id, Id arg_id)
451 {
452         Id result_id = begin_expression(opcode, type_id, 1);
453         writer.write(arg_id);
454         end_expression(opcode);
455         return result_id;
456 }
457
458 SpirVGenerator::Id SpirVGenerator::write_expression(Opcode opcode, Id type_id, Id left_id, Id right_id)
459 {
460         Id result_id = begin_expression(opcode, type_id, 2);
461         writer.write(left_id);
462         writer.write(right_id);
463         end_expression(opcode);
464         return result_id;
465 }
466
467 void SpirVGenerator::write_deconstruct(Id elem_type_id, Id composite_id, Id *elem_ids, unsigned n_elems)
468 {
469         for(unsigned i=0; i<n_elems; ++i)
470         {
471                 elem_ids[i] = begin_expression(OP_COMPOSITE_EXTRACT, elem_type_id, 2);
472                 writer.write(composite_id);
473                 writer.write(i);
474                 end_expression(OP_COMPOSITE_EXTRACT);
475         }
476 }
477
478 SpirVGenerator::Id SpirVGenerator::write_construct(Id type_id, const Id *elem_ids, unsigned n_elems)
479 {
480         Id result_id = begin_expression(OP_COMPOSITE_CONSTRUCT, type_id, n_elems);
481         for(unsigned i=0; i<n_elems; ++i)
482                 writer.write(elem_ids[i]);
483         end_expression(OP_COMPOSITE_CONSTRUCT);
484
485         return result_id;
486 }
487
488 void SpirVGenerator::visit(Block &block)
489 {
490         for(const RefPtr<Statement> &s: block.body)
491                 s->visit(*this);
492 }
493
494 void SpirVGenerator::visit(Literal &literal)
495 {
496         Id type_id = get_id(*literal.type);
497         if(spec_constant)
498                 r_expression_result_id = write_constant(type_id, get_constant_key(type_id, literal.value).int_value, true);
499         else
500                 r_expression_result_id = get_constant_id(type_id, literal.value);
501         r_constant_result = true;
502 }
503
504 void SpirVGenerator::visit(VariableReference &var)
505 {
506         if(constant_expression || var.declaration->constant)
507         {
508                 if(!var.declaration->constant)
509                         throw internal_error("reference to non-constant variable in constant context");
510
511                 r_expression_result_id = get_id(*var.declaration);
512                 r_constant_result = true;
513                 return;
514         }
515         else if(!current_function)
516                 throw internal_error("non-constant context outside a function");
517
518         r_constant_result = false;
519         if(composite_access)
520         {
521                 r_expression_result_id = 0;
522                 if(!assignment_source_id)
523                 {
524                         auto i = variable_load_ids.find(var.declaration);
525                         if(i!=variable_load_ids.end())
526                                 r_expression_result_id = i->second;
527                 }
528                 if(!r_expression_result_id)
529                         r_composite_base = var.declaration;
530         }
531         else if(assignment_source_id)
532         {
533                 writer.write_op(content.function_body, OP_STORE, get_id(*var.declaration), assignment_source_id);
534                 variable_load_ids[var.declaration] = assignment_source_id;
535                 r_expression_result_id = assignment_source_id;
536         }
537         else
538                 r_expression_result_id = get_load_id(*var.declaration);
539 }
540
541 void SpirVGenerator::visit(InterfaceBlockReference &iface)
542 {
543         if(!composite_access || !current_function)
544                 throw internal_error("invalid interface block reference");
545
546         r_composite_base = iface.declaration;
547         r_expression_result_id = 0;
548         r_constant_result = false;
549 }
550
551 void SpirVGenerator::generate_composite_access(TypeDeclaration &result_type)
552 {
553         Opcode opcode;
554         Id result_type_id = get_id(result_type);
555         Id access_type_id = result_type_id;
556         if(r_composite_base)
557         {
558                 if(constant_expression)
559                         throw internal_error("composite access through pointer in constant context");
560
561                 Id int32_type_id = get_standard_type_id(BasicTypeDeclaration::INT, 1);
562                 for(unsigned &i: r_composite_chain)
563                         i = (i<0x400000 ? get_constant_id(int32_type_id, static_cast<int>(i)) : i&0x3FFFFF);
564
565                 /* Find the storage class of the base and obtain appropriate pointer type
566                 for the result. */
567                 const Declaration &base_decl = get_item(declared_ids, r_composite_base);
568                 auto i = pointer_type_ids.begin();
569                 for(; (i!=pointer_type_ids.end() && i->second!=base_decl.type_id); ++i) ;
570                 if(i==pointer_type_ids.end())
571                         throw internal_error("could not find storage class");
572                 access_type_id = get_pointer_type_id(result_type_id, static_cast<StorageClass>(i->first.detail));
573
574                 opcode = OP_ACCESS_CHAIN;
575         }
576         else if(assignment_source_id)
577                 throw internal_error("assignment to temporary composite");
578         else
579         {
580                 for(unsigned &i: r_composite_chain)
581                         for(auto j=constant_ids.begin(); (i>=0x400000 && j!=constant_ids.end()); ++j)
582                                 if(j->second==(i&0x3FFFFF))
583                                         i = j->first.int_value;
584
585                 opcode = OP_COMPOSITE_EXTRACT;
586         }
587
588         Id access_id = begin_expression(opcode, access_type_id, 1+r_composite_chain.size());
589         writer.write(r_composite_base_id);
590         for(unsigned i: r_composite_chain)
591                 writer.write(i);
592         end_expression(opcode);
593
594         r_constant_result = false;
595         if(r_composite_base)
596         {
597                 if(assignment_source_id)
598                 {
599                         writer.write_op(content.function_body, OP_STORE, access_id, assignment_source_id);
600                         r_expression_result_id = assignment_source_id;
601                 }
602                 else
603                         r_expression_result_id = write_expression(OP_LOAD, result_type_id, access_id);
604         }
605         else
606                 r_expression_result_id = access_id;
607 }
608
609 void SpirVGenerator::visit_composite(Expression &base_expr, unsigned index, TypeDeclaration &type)
610 {
611         if(!composite_access)
612         {
613                 r_composite_base = 0;
614                 r_composite_base_id = 0;
615                 r_composite_chain.clear();
616         }
617
618         {
619                 SetFlag set_composite(composite_access);
620                 base_expr.visit(*this);
621         }
622
623         if(!r_composite_base_id)
624                 r_composite_base_id = (r_composite_base ? get_id(*r_composite_base) : r_expression_result_id);
625
626         r_composite_chain.push_back(index);
627         if(!composite_access)
628                 generate_composite_access(type);
629         else
630                 r_expression_result_id = 0;
631 }
632
633 void SpirVGenerator::visit_isolated(Expression &expr)
634 {
635         SetForScope<Id> clear_assign(assignment_source_id, 0);
636         SetFlag clear_composite(composite_access, false);
637         SetForScope<Node *> clear_base(r_composite_base, 0);
638         SetForScope<Id> clear_base_id(r_composite_base_id, 0);
639         vector<unsigned> saved_chain;
640         swap(saved_chain, r_composite_chain);
641         expr.visit(*this);
642         swap(saved_chain, r_composite_chain);
643 }
644
645 void SpirVGenerator::visit(MemberAccess &memacc)
646 {
647         visit_composite(*memacc.left, memacc.index, *memacc.type);
648 }
649
650 void SpirVGenerator::visit(Swizzle &swizzle)
651 {
652         if(swizzle.count==1)
653                 visit_composite(*swizzle.left, swizzle.components[0], *swizzle.type);
654         else if(assignment_source_id)
655         {
656                 const BasicTypeDeclaration &basic = dynamic_cast<const BasicTypeDeclaration &>(*swizzle.left->type);
657
658                 unsigned mask = 0;
659                 for(unsigned i=0; i<swizzle.count; ++i)
660                         mask |= 1<<swizzle.components[i];
661
662                 visit_isolated(*swizzle.left);
663
664                 Id combined_id = begin_expression(OP_VECTOR_SHUFFLE, get_id(*swizzle.left->type), 2+basic.size);
665                 writer.write(r_expression_result_id);
666                 writer.write(assignment_source_id);
667                 for(unsigned i=0; i<basic.size; ++i)
668                         writer.write(i+((mask>>i)&1)*basic.size);
669                 end_expression(OP_VECTOR_SHUFFLE);
670
671                 SetForScope<Id> set_assign(assignment_source_id, combined_id);
672                 swizzle.left->visit(*this);
673
674                 r_expression_result_id = combined_id;
675         }
676         else
677         {
678                 swizzle.left->visit(*this);
679                 Id left_id = r_expression_result_id;
680
681                 r_expression_result_id = begin_expression(OP_VECTOR_SHUFFLE, get_id(*swizzle.type), 2+swizzle.count);
682                 writer.write(left_id);
683                 writer.write(left_id);
684                 for(unsigned i=0; i<swizzle.count; ++i)
685                         writer.write(swizzle.components[i]);
686                 end_expression(OP_VECTOR_SHUFFLE);
687         }
688         r_constant_result = false;
689 }
690
691 void SpirVGenerator::visit(UnaryExpression &unary)
692 {
693         if(composite_access)
694                 return visit_isolated(unary);
695
696         unary.expression->visit(*this);
697
698         char oper = unary.oper->token[0];
699         char oper2 = unary.oper->token[1];
700         if(oper=='+' && !oper2)
701                 return;
702
703         BasicTypeDeclaration &basic = dynamic_cast<BasicTypeDeclaration &>(*unary.expression->type);
704         BasicTypeDeclaration &elem = *get_element_type(basic);
705
706         if(constant_expression && elem.kind!=BasicTypeDeclaration::BOOL && elem.kind!=BasicTypeDeclaration::INT)
707                 /* SPIR-V allows constant operations on floating-point values only for
708                 OpenGL kernels. */
709                 throw internal_error("invalid operands for constant unary expression");
710
711         Id result_type_id = get_id(*unary.type);
712         Opcode opcode = OP_NOP;
713
714         r_constant_result = false;
715         if(oper=='!')
716                 opcode = OP_LOGICAL_NOT;
717         else if(oper=='~')
718                 opcode = OP_NOT;
719         else if(oper=='-' && !oper2)
720         {
721                 opcode = (elem.kind==BasicTypeDeclaration::INT ? OP_S_NEGATE : OP_F_NEGATE);
722
723                 if(basic.kind==BasicTypeDeclaration::MATRIX)
724                 {
725                         Id column_type_id = get_id(*basic.base_type);
726                         unsigned n_columns = basic.size&0xFFFF;
727                         Id column_ids[4];
728                         write_deconstruct(column_type_id, r_expression_result_id, column_ids, n_columns);
729                         for(unsigned i=0; i<n_columns; ++i)
730                                 column_ids[i] = write_expression(opcode, column_type_id, column_ids[i]);
731                         r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
732                         return;
733                 }
734         }
735         else if((oper=='+' || oper=='-') && oper2==oper)
736         {
737                 if(constant_expression)
738                         throw internal_error("increment or decrement in constant expression");
739
740                 Id one_id = 0;
741                 if(elem.kind==BasicTypeDeclaration::INT)
742                 {
743                         opcode = (oper=='+' ? OP_I_ADD : OP_I_SUB);
744                         one_id = get_constant_id(get_id(elem), 1);
745                 }
746                 else if(elem.kind==BasicTypeDeclaration::FLOAT)
747                 {
748                         opcode = (oper=='+' ? OP_F_ADD : OP_F_SUB);
749                         one_id = get_constant_id(get_id(elem), 1.0f);
750                 }
751                 else
752                         throw internal_error("invalid increment/decrement");
753
754                 if(basic.kind==BasicTypeDeclaration::VECTOR)
755                         one_id = get_vector_constant_id(result_type_id, basic.size, one_id);
756
757                 Id post_value_id = write_expression(opcode, result_type_id, r_expression_result_id, one_id);
758
759                 SetForScope<Id> set_assign(assignment_source_id, post_value_id);
760                 unary.expression->visit(*this);
761
762                 r_expression_result_id = (unary.oper->type==Operator::POSTFIX ? r_expression_result_id : post_value_id);
763                 return;
764         }
765
766         if(opcode==OP_NOP)
767                 throw internal_error("unknown unary operator");
768
769         r_expression_result_id = write_expression(opcode, result_type_id, r_expression_result_id);
770 }
771
772 void SpirVGenerator::visit(BinaryExpression &binary)
773 {
774         char oper = binary.oper->token[0];
775         if(oper=='[')
776         {
777                 visit_isolated(*binary.right);
778                 return visit_composite(*binary.left, 0x400000|r_expression_result_id, *binary.type);
779         }
780         else if(composite_access)
781                 return visit_isolated(binary);
782
783         if(assignment_source_id)
784                 throw internal_error("invalid binary expression in assignment target");
785
786         BasicTypeDeclaration &basic_left = dynamic_cast<BasicTypeDeclaration &>(*binary.left->type);
787         BasicTypeDeclaration &basic_right = dynamic_cast<BasicTypeDeclaration &>(*binary.right->type);
788         // Expression resolver ensures that element types are the same
789         BasicTypeDeclaration &elem = *get_element_type(basic_left);
790
791         if(constant_expression && elem.kind!=BasicTypeDeclaration::BOOL && elem.kind!=BasicTypeDeclaration::INT)
792                 /* SPIR-V allows constant operations on floating-point values only for
793                 OpenGL kernels. */
794                 throw internal_error("invalid operands for constant binary expression");
795
796         binary.left->visit(*this);
797         Id left_id = r_expression_result_id;
798         binary.right->visit(*this);
799         Id right_id = r_expression_result_id;
800
801         Id result_type_id = get_id(*binary.type);
802         Opcode opcode = OP_NOP;
803         bool swap_operands = false;
804
805         r_constant_result = false;
806
807         char oper2 = binary.oper->token[1];
808         if((oper=='<' || oper=='>') && oper2!=oper)
809         {
810                 if(basic_left.kind==BasicTypeDeclaration::INT)
811                 {
812                         if(basic_left.sign)
813                                 opcode = (oper=='<' ? (oper2=='=' ? OP_S_LESS_THAN_EQUAL : OP_S_LESS_THAN) :
814                                         (oper2=='=' ? OP_S_GREATER_THAN_EQUAL : OP_S_GREATER_THAN));
815                         else
816                                 opcode = (oper=='<' ? (oper2=='=' ? OP_U_LESS_THAN_EQUAL : OP_U_LESS_THAN) :
817                                         (oper2=='=' ? OP_U_GREATER_THAN_EQUAL : OP_U_GREATER_THAN));
818                 }
819                 else if(basic_left.kind==BasicTypeDeclaration::FLOAT)
820                         opcode = (oper=='<' ? (oper2=='=' ? OP_F_ORD_LESS_THAN_EQUAL : OP_F_ORD_LESS_THAN) :
821                                 (oper2=='=' ? OP_F_ORD_GREATER_THAN_EQUAL : OP_F_ORD_GREATER_THAN));
822         }
823         else if((oper=='=' || oper=='!') && oper2=='=')
824         {
825                 if(elem.kind==BasicTypeDeclaration::BOOL)
826                         opcode = (oper=='=' ? OP_LOGICAL_EQUAL : OP_LOGICAL_NOT_EQUAL);
827                 else if(elem.kind==BasicTypeDeclaration::INT)
828                         opcode = (oper=='=' ? OP_I_EQUAL : OP_I_NOT_EQUAL);
829                 else if(elem.kind==BasicTypeDeclaration::FLOAT)
830                         opcode = (oper=='=' ? OP_F_ORD_EQUAL : OP_F_ORD_NOT_EQUAL);
831
832                 if(opcode!=OP_NOP && basic_left.base_type)
833                 {
834                         /* The SPIR-V equality operations produce component-wise results, but
835                         GLSL operators return a single boolean.  Use the any/all operations to
836                         combine the results. */
837                         Opcode combine_op = (oper=='!' ? OP_ANY : OP_ALL);
838                         unsigned n_elems = basic_left.size&0xFFFF;
839                         Id bool_vec_type_id = get_standard_type_id(BasicTypeDeclaration::BOOL, n_elems);
840
841                         Id compare_id = 0;
842                         if(basic_left.kind==BasicTypeDeclaration::VECTOR)
843                                 compare_id = write_expression(opcode, bool_vec_type_id, left_id, right_id);
844                         else if(basic_left.kind==BasicTypeDeclaration::MATRIX)
845                         {
846                                 Id column_type_id = get_id(*basic_left.base_type);
847                                 Id column_ids[8];
848                                 write_deconstruct(column_type_id, left_id, column_ids, n_elems);
849                                 write_deconstruct(column_type_id, right_id, column_ids+4, n_elems);
850
851                                 Id column_bvec_type_id = get_standard_type_id(BasicTypeDeclaration::BOOL, basic_left.size>>16);
852                                 for(unsigned i=0; i<n_elems; ++i)
853                                 {
854                                         compare_id = write_expression(opcode, column_bvec_type_id, column_ids[i], column_ids[4+i]);
855                                         column_ids[i] = write_expression(combine_op, result_type_id, compare_id);;
856                                 }
857
858                                 compare_id = write_construct(bool_vec_type_id, column_ids, n_elems);
859                         }
860
861                         if(compare_id)
862                                 r_expression_result_id = write_expression(combine_op, result_type_id, compare_id);
863                         return;
864                 }
865         }
866         else if(oper2=='&' && elem.kind==BasicTypeDeclaration::BOOL)
867                 opcode = OP_LOGICAL_AND;
868         else if(oper2=='|' && elem.kind==BasicTypeDeclaration::BOOL)
869                 opcode = OP_LOGICAL_OR;
870         else if(oper2=='^' && elem.kind==BasicTypeDeclaration::BOOL)
871                 opcode = OP_LOGICAL_NOT_EQUAL;
872         else if(oper=='&' && elem.kind==BasicTypeDeclaration::INT)
873                 opcode = OP_BITWISE_AND;
874         else if(oper=='|' && elem.kind==BasicTypeDeclaration::INT)
875                 opcode = OP_BITWISE_OR;
876         else if(oper=='^' && elem.kind==BasicTypeDeclaration::INT)
877                 opcode = OP_BITWISE_XOR;
878         else if(oper=='<' && oper2==oper && elem.kind==BasicTypeDeclaration::INT)
879                 opcode = OP_SHIFT_LEFT_LOGICAL;
880         else if(oper=='>' && oper2==oper && elem.kind==BasicTypeDeclaration::INT)
881                 opcode = OP_SHIFT_RIGHT_ARITHMETIC;
882         else if(oper=='%' && elem.kind==BasicTypeDeclaration::INT)
883                 opcode = (elem.sign ? OP_S_MOD : OP_U_MOD);
884         else if(oper=='+' || oper=='-' || oper=='*' || oper=='/')
885         {
886                 Opcode elem_op = OP_NOP;
887                 if(elem.kind==BasicTypeDeclaration::INT)
888                 {
889                         if(oper=='/')
890                                 elem_op = (elem.sign ? OP_S_DIV : OP_U_DIV);
891                         else
892                                 elem_op = (oper=='+' ? OP_I_ADD : oper=='-' ? OP_I_SUB : OP_I_MUL);
893                 }
894                 else if(elem.kind==BasicTypeDeclaration::FLOAT)
895                         elem_op = (oper=='+' ? OP_F_ADD : oper=='-' ? OP_F_SUB : oper=='*' ? OP_F_MUL : OP_F_DIV);
896
897                 if(oper=='*' && (basic_left.base_type || basic_right.base_type) && elem.kind==BasicTypeDeclaration::FLOAT)
898                 {
899                         /* Multiplication between floating-point vectors and matrices has
900                         dedicated operations. */
901                         if(basic_left.kind==BasicTypeDeclaration::MATRIX && basic_right.kind==BasicTypeDeclaration::MATRIX)
902                                 opcode = OP_MATRIX_TIMES_MATRIX;
903                         else if(basic_left.kind==BasicTypeDeclaration::MATRIX || basic_right.kind==BasicTypeDeclaration::MATRIX)
904                         {
905                                 if(basic_left.kind==BasicTypeDeclaration::VECTOR)
906                                         opcode = OP_VECTOR_TIMES_MATRIX;
907                                 else if(basic_right.kind==BasicTypeDeclaration::VECTOR)
908                                         opcode = OP_MATRIX_TIMES_VECTOR;
909                                 else
910                                 {
911                                         opcode = OP_MATRIX_TIMES_SCALAR;
912                                         swap_operands = (basic_right.kind==BasicTypeDeclaration::MATRIX);
913                                 }
914                         }
915                         else if(basic_left.kind==BasicTypeDeclaration::VECTOR && basic_right.kind==BasicTypeDeclaration::VECTOR)
916                                 opcode = elem_op;
917                         else
918                         {
919                                 opcode = OP_VECTOR_TIMES_SCALAR;
920                                 swap_operands = (basic_right.kind==BasicTypeDeclaration::VECTOR);
921                         }
922                 }
923                 else if((basic_left.base_type!=0)!=(basic_right.base_type!=0))
924                 {
925                         /* One operand is scalar and the other is a vector or a matrix.
926                         Expand the scalar to a vector of appropriate size. */
927                         Id &scalar_id = (basic_left.base_type ? right_id : left_id);
928                         BasicTypeDeclaration *vector_type = (basic_left.base_type ? &basic_left : &basic_right);
929                         if(vector_type->kind==BasicTypeDeclaration::MATRIX)
930                                 vector_type = dynamic_cast<BasicTypeDeclaration *>(vector_type->base_type);
931                         Id vector_type_id = get_id(*vector_type);
932
933                         Id expanded_id = begin_expression(OP_COMPOSITE_CONSTRUCT, vector_type_id, vector_type->size);
934                         for(unsigned i=0; i<vector_type->size; ++i)
935                                 writer.write(scalar_id);
936                         end_expression(OP_COMPOSITE_CONSTRUCT);
937
938                         scalar_id = expanded_id;
939
940                         if(basic_left.kind==BasicTypeDeclaration::MATRIX || basic_right.kind==BasicTypeDeclaration::MATRIX)
941                         {
942                                 // Apply matrix operation column-wise.
943                                 Id matrix_id = (basic_left.base_type ? left_id : right_id);
944
945                                 Id column_ids[4];
946                                 unsigned n_columns = (basic_left.base_type ? basic_left.size : basic_right.size)&0xFFFF;
947                                 write_deconstruct(vector_type_id, matrix_id, column_ids, n_columns);
948
949                                 for(unsigned i=0; i<n_columns; ++i)
950                                         column_ids[i] = write_expression(elem_op, vector_type_id, column_ids[i], expanded_id);
951
952                                 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
953                                 return;
954                         }
955                         else
956                                 opcode = elem_op;
957                 }
958                 else if(basic_left.kind==BasicTypeDeclaration::MATRIX && basic_right.kind==BasicTypeDeclaration::MATRIX)
959                 {
960                         if(oper=='*')
961                                 throw internal_error("non-float matrix multiplication");
962
963                         /* Other operations involving matrices need to be performed
964                         column-wise. */
965                         Id column_type_id = get_id(*basic_left.base_type);
966                         Id column_ids[8];
967
968                         unsigned n_columns = basic_left.size&0xFFFF;
969                         write_deconstruct(column_type_id, left_id, column_ids, n_columns);
970                         write_deconstruct(column_type_id, right_id, column_ids+4, n_columns);
971
972                         for(unsigned i=0; i<n_columns; ++i)
973                                 column_ids[i] = write_expression(elem_op, column_type_id, column_ids[i], column_ids[4+i]);
974
975                         r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
976                         return;
977                 }
978                 else if(basic_left.kind==basic_right.kind)
979                         // Both operands are either scalars or vectors.
980                         opcode = elem_op;
981         }
982
983         if(opcode==OP_NOP)
984                 throw internal_error("unknown binary operator");
985
986         if(swap_operands)
987                 swap(left_id, right_id);
988
989         r_expression_result_id = write_expression(opcode, result_type_id, left_id, right_id);
990 }
991
992 void SpirVGenerator::visit(Assignment &assign)
993 {
994         if(assign.oper->token[0]!='=')
995                 visit(static_cast<BinaryExpression &>(assign));
996         else
997                 assign.right->visit(*this);
998
999         SetForScope<Id> set_assign(assignment_source_id, r_expression_result_id);
1000         assign.left->visit(*this);
1001         r_constant_result = false;
1002 }
1003
1004 void SpirVGenerator::visit(TernaryExpression &ternary)
1005 {
1006         if(composite_access)
1007                 return visit_isolated(ternary);
1008         if(constant_expression)
1009         {
1010                 ternary.condition->visit(*this);
1011                 Id condition_id = r_expression_result_id;
1012                 ternary.true_expr->visit(*this);
1013                 Id true_result_id = r_expression_result_id;
1014                 ternary.false_expr->visit(*this);
1015                 Id false_result_id = r_expression_result_id;
1016
1017                 r_expression_result_id = begin_expression(OP_SELECT, get_id(*ternary.type), 3);
1018                 writer.write(condition_id);
1019                 writer.write(true_result_id);
1020                 writer.write(false_result_id);
1021                 end_expression(OP_SELECT);
1022
1023                 return;
1024         }
1025
1026         ternary.condition->visit(*this);
1027         Id condition_id = r_expression_result_id;
1028
1029         Id true_label_id = next_id++;
1030         Id false_label_id = next_id++;
1031         Id merge_block_id = next_id++;
1032         writer.write_op(content.function_body, OP_SELECTION_MERGE, merge_block_id, 0);  // Selection control (none)
1033         writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, condition_id, true_label_id, false_label_id);
1034
1035         writer.write_op_label(true_label_id);
1036         ternary.true_expr->visit(*this);
1037         Id true_result_id = r_expression_result_id;
1038         true_label_id = writer.get_current_block();
1039         writer.write_op(content.function_body, OP_BRANCH, merge_block_id);
1040
1041         writer.write_op_label(false_label_id);
1042         ternary.false_expr->visit(*this);
1043         Id false_result_id = r_expression_result_id;
1044         false_label_id = writer.get_current_block();
1045
1046         writer.write_op_label(merge_block_id);
1047         r_expression_result_id = begin_expression(OP_PHI, get_id(*ternary.type), 4);
1048         writer.write(true_result_id);
1049         writer.write(true_label_id);
1050         writer.write(false_result_id);
1051         writer.write(false_label_id);
1052         end_expression(OP_PHI);
1053
1054         r_constant_result = false;
1055 }
1056
1057 void SpirVGenerator::visit(FunctionCall &call)
1058 {
1059         if(assignment_source_id)
1060                 throw internal_error("assignment to function call");
1061         else if(composite_access)
1062                 return visit_isolated(call);
1063         else if(call.constructor && call.arguments.size()==1 && call.arguments[0]->type==call.type)
1064                 return call.arguments[0]->visit(*this);
1065
1066         vector<Id> argument_ids;
1067         argument_ids.reserve(call.arguments.size());
1068         bool all_args_const = true;
1069         for(const RefPtr<Expression> &a: call.arguments)
1070         {
1071                 a->visit(*this);
1072                 argument_ids.push_back(r_expression_result_id);
1073                 all_args_const &= r_constant_result;
1074         }
1075
1076         if(constant_expression && (!call.constructor || !all_args_const))
1077                 throw internal_error("function call in constant expression");
1078
1079         Id result_type_id = get_id(*call.type);
1080         r_constant_result = false;
1081
1082         if(call.constructor)
1083                 visit_constructor(call, argument_ids, all_args_const);
1084         else if(call.declaration->source==BUILTIN_SOURCE)
1085         {
1086                 string arg_types;
1087                 for(const RefPtr<Expression> &a: call.arguments)
1088                         if(BasicTypeDeclaration *basic_arg = dynamic_cast<BasicTypeDeclaration *>(a->type))
1089                         {
1090                                 BasicTypeDeclaration &elem_arg = *get_element_type(*basic_arg);
1091                                 switch(elem_arg.kind)
1092                                 {
1093                                 case BasicTypeDeclaration::BOOL: arg_types += 'b'; break;
1094                                 case BasicTypeDeclaration::INT: arg_types += (elem_arg.sign ? 'i' : 'u'); break;
1095                                 case BasicTypeDeclaration::FLOAT: arg_types += 'f'; break;
1096                                 default: arg_types += '?';
1097                                 }
1098                         }
1099
1100                 const BuiltinFunctionInfo *builtin_info;
1101                 for(builtin_info=builtin_functions; builtin_info->function[0]; ++builtin_info)
1102                         if(builtin_info->function==call.name && (!builtin_info->arg_types[0] || builtin_info->arg_types==arg_types))
1103                                 break;
1104
1105                 if(builtin_info->capability)
1106                         use_capability(static_cast<Capability>(builtin_info->capability));
1107
1108                 if(builtin_info->opcode)
1109                 {
1110                         Opcode opcode;
1111                         if(builtin_info->extension[0])
1112                         {
1113                                 opcode = OP_EXT_INST;
1114                                 Id ext_id = import_extension(builtin_info->extension);
1115
1116                                 r_expression_result_id = begin_expression(opcode, result_type_id);
1117                                 writer.write(ext_id);
1118                                 writer.write(builtin_info->opcode);
1119                         }
1120                         else
1121                         {
1122                                 opcode = static_cast<Opcode>(builtin_info->opcode);
1123                                 r_expression_result_id = begin_expression(opcode, result_type_id);
1124                         }
1125
1126                         for(unsigned i=0; i<call.arguments.size(); ++i)
1127                         {
1128                                 if(!builtin_info->arg_order[i] || builtin_info->arg_order[i]>argument_ids.size())
1129                                         throw internal_error("invalid builtin function info");
1130                                 writer.write(argument_ids[builtin_info->arg_order[i]-1]);
1131                         }
1132
1133                         end_expression(opcode);
1134                 }
1135                 else if(builtin_info->handler)
1136                         (this->*(builtin_info->handler))(call, argument_ids);
1137                 else
1138                         throw internal_error("unknown builtin function "+call.name);
1139         }
1140         else
1141         {
1142                 r_expression_result_id = begin_expression(OP_FUNCTION_CALL, result_type_id, 1+call.arguments.size());
1143                 writer.write(get_id(*call.declaration->definition));
1144                 for(Id i: argument_ids)
1145                         writer.write(i);
1146                 end_expression(OP_FUNCTION_CALL);
1147
1148                 // Any global variables the called function uses might have changed value
1149                 set<Node *> dependencies = DependencyCollector().apply(*call.declaration->definition);
1150                 for(Node *n: dependencies)
1151                         if(const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(n))
1152                                 variable_load_ids.erase(var);
1153         }
1154 }
1155
1156 void SpirVGenerator::visit_constructor(FunctionCall &call, const vector<Id> &argument_ids, bool all_args_const)
1157 {
1158         Id result_type_id = get_id(*call.type);
1159
1160         BasicTypeDeclaration *basic = dynamic_cast<BasicTypeDeclaration *>(call.type);
1161         if(!basic)
1162         {
1163                 if(dynamic_cast<const StructDeclaration *>(call.type))
1164                         r_expression_result_id = write_construct(result_type_id, &argument_ids[0], argument_ids.size());
1165                 else
1166                         throw internal_error("unconstructable type "+call.name);
1167                 return;
1168         }
1169
1170         SetFlag set_const(constant_expression, constant_expression || all_args_const);
1171
1172         BasicTypeDeclaration &elem = *get_element_type(*basic);
1173         BasicTypeDeclaration &basic_arg0 = dynamic_cast<BasicTypeDeclaration &>(*call.arguments[0]->type);
1174         BasicTypeDeclaration &elem_arg0 = *get_element_type(basic_arg0);
1175
1176         if(basic->kind==BasicTypeDeclaration::MATRIX)
1177         {
1178                 Id col_type_id = get_id(*basic->base_type);
1179                 unsigned n_columns = basic->size&0xFFFF;
1180                 unsigned n_rows = basic->size>>16;
1181
1182                 Id column_ids[4];
1183                 if(call.arguments.size()==1)
1184                 {
1185                         // Construct diagonal matrix from a single scalar.
1186                         Id zero_id = get_constant_id(get_id(elem), 0.0f);
1187                         for(unsigned i=0; i<n_columns; ++i)
1188                         {
1189                                 column_ids[i] = begin_expression(OP_COMPOSITE_CONSTRUCT, col_type_id, n_rows);
1190                                 for(unsigned j=0; j<n_rows; ++j)
1191                                         writer.write(j==i ? argument_ids[0] : zero_id);
1192                                 end_expression(OP_COMPOSITE_CONSTRUCT);
1193                         }
1194                 }
1195                 else
1196                         // Construct a matrix from column vectors
1197                         copy(argument_ids.begin(), argument_ids.begin()+n_columns, column_ids);
1198
1199                 r_expression_result_id = write_construct(result_type_id, column_ids, n_columns);
1200         }
1201         else if(basic->kind==BasicTypeDeclaration::VECTOR && (call.arguments.size()>1 || basic_arg0.kind!=BasicTypeDeclaration::VECTOR))
1202         {
1203                 /* There's either a single scalar argument or multiple arguments
1204                 which make up the vector's components. */
1205                 if(call.arguments.size()==1)
1206                 {
1207                         r_expression_result_id = begin_expression(OP_COMPOSITE_CONSTRUCT, result_type_id);
1208                         for(unsigned i=0; i<basic->size; ++i)
1209                                 writer.write(argument_ids[0]);
1210                         end_expression(OP_COMPOSITE_CONSTRUCT);
1211                 }
1212                 else
1213                         r_expression_result_id = write_construct(result_type_id, &argument_ids[0], argument_ids.size());
1214         }
1215         else if(elem.kind==BasicTypeDeclaration::BOOL)
1216         {
1217                 if(constant_expression)
1218                         throw internal_error("unconverted constant");
1219
1220                 // Conversion to boolean is implemented as comparing against zero.
1221                 Id number_type_id = get_id(elem_arg0);
1222                 Id zero_id = (elem_arg0.kind==BasicTypeDeclaration::FLOAT ?
1223                         get_constant_id(number_type_id, 0.0f) : get_constant_id(number_type_id, 0));
1224                 if(basic_arg0.kind==BasicTypeDeclaration::VECTOR)
1225                         zero_id = get_vector_constant_id(get_id(basic_arg0), basic_arg0.size, zero_id);
1226
1227                 Opcode opcode = (elem_arg0.kind==BasicTypeDeclaration::FLOAT ? OP_F_ORD_NOT_EQUAL : OP_I_NOT_EQUAL);
1228                 r_expression_result_id = write_expression(opcode, result_type_id, argument_ids[0], zero_id);
1229         }
1230         else if(elem_arg0.kind==BasicTypeDeclaration::BOOL)
1231         {
1232                 if(constant_expression)
1233                         throw internal_error("unconverted constant");
1234
1235                 /* Conversion from boolean is implemented as selecting from zero
1236                 or one. */
1237                 Id number_type_id = get_id(elem);
1238                 Id zero_id = (elem.kind==BasicTypeDeclaration::FLOAT ?
1239                         get_constant_id(number_type_id, 0.0f) : get_constant_id(number_type_id, 0));
1240                 Id one_id = (elem.kind==BasicTypeDeclaration::FLOAT ?
1241                         get_constant_id(number_type_id, 1.0f) : get_constant_id(number_type_id, 1));
1242                 if(basic->kind==BasicTypeDeclaration::VECTOR)
1243                 {
1244                         zero_id = get_vector_constant_id(get_id(*basic), basic->size, zero_id);
1245                         one_id = get_vector_constant_id(get_id(*basic), basic->size, one_id);
1246                 }
1247
1248                 r_expression_result_id = begin_expression(OP_SELECT, result_type_id, 3);
1249                 writer.write(argument_ids[0]);
1250                 writer.write(zero_id);
1251                 writer.write(one_id);
1252                 end_expression(OP_SELECT);
1253         }
1254         else
1255         {
1256                 if(constant_expression)
1257                         throw internal_error("unconverted constant");
1258
1259                 // Scalar or vector conversion between types of equal size.
1260                 Opcode opcode;
1261                 if(elem.kind==BasicTypeDeclaration::INT && elem_arg0.kind==BasicTypeDeclaration::FLOAT)
1262                         opcode = (elem.sign ? OP_CONVERT_F_TO_S : OP_CONVERT_F_TO_U);
1263                 else if(elem.kind==BasicTypeDeclaration::FLOAT && elem_arg0.kind==BasicTypeDeclaration::INT)
1264                         opcode = (elem_arg0.sign ? OP_CONVERT_S_TO_F : OP_CONVERT_U_TO_F);
1265                 else if(elem.kind==BasicTypeDeclaration::INT && elem_arg0.kind==BasicTypeDeclaration::INT)
1266                         opcode = OP_BITCAST;
1267                 else
1268                         throw internal_error("invalid conversion");
1269
1270                 r_expression_result_id = write_expression(opcode, result_type_id, argument_ids[0]);
1271         }
1272 }
1273
1274 void SpirVGenerator::visit_builtin_matrix_comp_mult(FunctionCall &call, const vector<Id> &argument_ids)
1275 {
1276         if(argument_ids.size()!=2)
1277                 throw internal_error("invalid matrixCompMult call");
1278
1279         const BasicTypeDeclaration &basic_arg0 = dynamic_cast<const BasicTypeDeclaration &>(*call.arguments[0]->type);
1280         Id column_type_id = get_id(*basic_arg0.base_type);
1281         Id column_ids[8];
1282
1283         unsigned n_columns = basic_arg0.size&0xFFFF;
1284         write_deconstruct(column_type_id, argument_ids[0], column_ids, n_columns);
1285         write_deconstruct(column_type_id, argument_ids[1], column_ids+4, n_columns);
1286
1287         for(unsigned i=0; i<n_columns; ++i)
1288                 column_ids[i] = write_expression(OP_F_MUL, column_type_id, column_ids[i], column_ids[4+i]);
1289
1290         r_expression_result_id = write_construct(get_id(*call.type), column_ids, n_columns);
1291 }
1292
1293 void SpirVGenerator::visit_builtin_texture_query(FunctionCall &call, const vector<Id> &argument_ids)
1294 {
1295         if(argument_ids.size()<1)
1296                 throw internal_error("invalid texture query call");
1297
1298         Opcode opcode;
1299         if(call.name=="textureSize")
1300                 opcode = OP_IMAGE_QUERY_SIZE_LOD;
1301         else if(call.name=="textureQueryLod")
1302                 opcode = OP_IMAGE_QUERY_LOD;
1303         else if(call.name=="textureQueryLevels")
1304                 opcode = OP_IMAGE_QUERY_LEVELS;
1305         else
1306                 throw internal_error("invalid texture query call");
1307
1308         ImageTypeDeclaration &image_arg0 = dynamic_cast<ImageTypeDeclaration &>(*call.arguments[0]->type);
1309
1310         Id image_id;
1311         if(image_arg0.sampled)
1312         {
1313                 Id image_type_id = get_item(image_type_ids, get_id(image_arg0));
1314                 image_id = write_expression(OP_IMAGE, image_type_id, argument_ids[0]);
1315         }
1316         else
1317                 image_id = argument_ids[0];
1318
1319         Id result_type_id = get_id(*call.type);
1320         r_expression_result_id = begin_expression(opcode, result_type_id, argument_ids.size());
1321         writer.write(image_id);
1322         for(unsigned i=1; i<argument_ids.size(); ++i)
1323                 writer.write(argument_ids[i]);
1324         end_expression(opcode);
1325 }
1326
1327 void SpirVGenerator::visit_builtin_texture(FunctionCall &call, const vector<Id> &argument_ids)
1328 {
1329         if(argument_ids.size()<2)
1330                 throw internal_error("invalid texture sampling call");
1331
1332         bool explicit_lod = (stage->type!=Stage::FRAGMENT || call.name=="textureLod");
1333         Id lod_id = (!explicit_lod ? 0 : call.name=="textureLod" ? argument_ids.back() :
1334                 get_constant_id(get_standard_type_id(BasicTypeDeclaration::FLOAT, 1), 0.0f));
1335
1336         const ImageTypeDeclaration &image = dynamic_cast<const ImageTypeDeclaration &>(*call.arguments[0]->type);
1337
1338         Opcode opcode;
1339         Id result_type_id = get_id(*call.type);
1340         Id dref_id = 0;
1341         if(image.shadow)
1342         {
1343                 if(argument_ids.size()==2)
1344                 {
1345                         const BasicTypeDeclaration &basic_arg1 = dynamic_cast<const BasicTypeDeclaration &>(*call.arguments[1]->type);
1346                         dref_id = begin_expression(OP_COMPOSITE_EXTRACT, get_id(*basic_arg1.base_type), 2);
1347                         writer.write(argument_ids.back());
1348                         writer.write(basic_arg1.size-1);
1349                         end_expression(OP_COMPOSITE_EXTRACT);
1350                 }
1351                 else
1352                         dref_id = argument_ids[2];
1353
1354                 opcode = (explicit_lod ? OP_IMAGE_SAMPLE_DREF_EXPLICIT_LOD : OP_IMAGE_SAMPLE_DREF_IMPLICIT_LOD);
1355                 r_expression_result_id = begin_expression(opcode, result_type_id, 3+explicit_lod*2);
1356         }
1357         else
1358         {
1359                 opcode = (explicit_lod ? OP_IMAGE_SAMPLE_EXPLICIT_LOD : OP_IMAGE_SAMPLE_IMPLICIT_LOD);
1360                 r_expression_result_id = begin_expression(opcode, result_type_id, 2+explicit_lod*2);
1361         }
1362
1363         for(unsigned i=0; i<2; ++i)
1364                 writer.write(argument_ids[i]);
1365         if(dref_id)
1366                 writer.write(dref_id);
1367         if(explicit_lod)
1368         {
1369                 writer.write(2);  // Lod
1370                 writer.write(lod_id);
1371         }
1372
1373         end_expression(opcode);
1374 }
1375
1376 void SpirVGenerator::visit_builtin_texel_fetch(FunctionCall &call, const vector<Id> &argument_ids)
1377 {
1378         if(argument_ids.size()!=3)
1379                 throw internal_error("invalid texelFetch call");
1380
1381         r_expression_result_id = begin_expression(OP_IMAGE_FETCH, get_id(*call.type), 4);
1382         for(unsigned i=0; i<2; ++i)
1383                 writer.write(argument_ids[i]);
1384         writer.write(2);  // Lod
1385         writer.write(argument_ids.back());
1386         end_expression(OP_IMAGE_FETCH);
1387 }
1388
1389 void SpirVGenerator::visit_builtin_interpolate(FunctionCall &call, const vector<Id> &argument_ids)
1390 {
1391         if(argument_ids.size()<1)
1392                 throw internal_error("invalid interpolate call");
1393         const VariableReference *var = dynamic_cast<const VariableReference *>(call.arguments[0].get());
1394         if(!var || !var->declaration || var->declaration->interface!="in")
1395                 throw internal_error("invalid interpolate call");
1396
1397         SpirVGlslStd450Opcode opcode;
1398         if(call.name=="interpolateAtCentroid")
1399                 opcode = GLSL450_INTERPOLATE_AT_CENTROID;
1400         else if(call.name=="interpolateAtSample")
1401                 opcode = GLSL450_INTERPOLATE_AT_SAMPLE;
1402         else if(call.name=="interpolateAtOffset")
1403                 opcode = GLSL450_INTERPOLATE_AT_OFFSET;
1404         else
1405                 throw internal_error("invalid interpolate call");
1406
1407         Id ext_id = import_extension("GLSL.std.450");
1408         r_expression_result_id = begin_expression(OP_EXT_INST, get_id(*call.type));
1409         writer.write(ext_id);
1410         writer.write(opcode);
1411         writer.write(get_id(*var->declaration));
1412         for(auto i=argument_ids.begin(); ++i!=argument_ids.end(); )
1413                 writer.write(*i);
1414         end_expression(OP_EXT_INST);
1415 }
1416
1417 void SpirVGenerator::visit(ExpressionStatement &expr)
1418 {
1419         expr.expression->visit(*this);
1420 }
1421
1422 void SpirVGenerator::visit(InterfaceLayout &layout)
1423 {
1424         interface_layouts.push_back(&layout);
1425 }
1426
1427 bool SpirVGenerator::check_duplicate_type(TypeDeclaration &type)
1428 {
1429         for(const auto &kvp: declared_ids)
1430                 if(TypeDeclaration *type2 = dynamic_cast<TypeDeclaration *>(kvp.first))
1431                         if(TypeComparer().apply(type, *type2))
1432                         {
1433                                 insert_unique(declared_ids, &type, kvp.second);
1434                                 return true;
1435                         }
1436
1437         return false;
1438 }
1439
1440 bool SpirVGenerator::check_standard_type(BasicTypeDeclaration &basic)
1441 {
1442         const BasicTypeDeclaration *elem = (basic.kind==BasicTypeDeclaration::VECTOR ?
1443                 dynamic_cast<const BasicTypeDeclaration *>(basic.base_type) : &basic);
1444         if(!elem || elem->base_type)
1445                 return false;
1446         if((elem->kind==BasicTypeDeclaration::INT || elem->kind==BasicTypeDeclaration::FLOAT) && elem->size!=32)
1447                 return false;
1448
1449         Id standard_id = get_standard_type_id(elem->kind, (basic.kind==BasicTypeDeclaration::VECTOR ? basic.size : 1), elem->sign);
1450         insert_unique(declared_ids, &basic, Declaration(standard_id, 0));
1451         writer.write_op_name(standard_id, basic.name);
1452
1453         return true;
1454 }
1455
1456 void SpirVGenerator::visit(BasicTypeDeclaration &basic)
1457 {
1458         if(check_standard_type(basic))
1459                 return;
1460         if(check_duplicate_type(basic))
1461                 return;
1462         // Alias types shouldn't exist at this point and arrays are handled elsewhere
1463         if(basic.kind==BasicTypeDeclaration::ALIAS || basic.kind==BasicTypeDeclaration::ARRAY)
1464                 return;
1465
1466         Id type_id = allocate_id(basic, 0);
1467         writer.write_op_name(type_id, basic.name);
1468
1469         switch(basic.kind)
1470         {
1471         case BasicTypeDeclaration::INT:
1472                 writer.write_op(content.globals, OP_TYPE_INT, type_id, basic.size, basic.sign);
1473                 break;
1474         case BasicTypeDeclaration::FLOAT:
1475                 writer.write_op(content.globals, OP_TYPE_FLOAT, type_id, basic.size);
1476                 break;
1477         case BasicTypeDeclaration::VECTOR:
1478                 writer.write_op(content.globals, OP_TYPE_VECTOR, type_id, get_id(*basic.base_type), basic.size);
1479                 break;
1480         case BasicTypeDeclaration::MATRIX:
1481                 writer.write_op(content.globals, OP_TYPE_MATRIX, type_id, get_id(*basic.base_type), basic.size&0xFFFF);
1482                 break;
1483         default:
1484                 throw internal_error("unknown basic type");
1485         }
1486 }
1487
1488 void SpirVGenerator::visit(ImageTypeDeclaration &image)
1489 {
1490         if(check_duplicate_type(image))
1491                 return;
1492
1493         Id type_id = allocate_id(image, 0);
1494
1495         Id image_id = (image.sampled ? next_id++ : type_id);
1496         writer.begin_op(content.globals, OP_TYPE_IMAGE, 9);
1497         writer.write(image_id);
1498         writer.write(get_id(*image.base_type));
1499         writer.write(image.dimensions-1);
1500         writer.write(image.shadow);
1501         writer.write(image.array);
1502         writer.write(false);  // Multisample
1503         writer.write(image.sampled ? 1 : 2);
1504         writer.write(0);  // Format (unknown)
1505         writer.end_op(OP_TYPE_IMAGE);
1506
1507         if(image.sampled)
1508         {
1509                 writer.write_op_name(type_id, image.name);
1510                 writer.write_op(content.globals, OP_TYPE_SAMPLED_IMAGE, type_id, image_id);
1511                 insert_unique(image_type_ids, type_id, image_id);
1512         }
1513
1514         if(image.dimensions==ImageTypeDeclaration::ONE)
1515                 use_capability(image.sampled ? CAP_SAMPLED_1D : CAP_IMAGE_1D);
1516         else if(image.dimensions==ImageTypeDeclaration::CUBE && image.array)
1517                 use_capability(image.sampled ? CAP_SAMPLED_CUBE_ARRAY : CAP_IMAGE_CUBE_ARRAY);
1518 }
1519
1520 void SpirVGenerator::visit(StructDeclaration &strct)
1521 {
1522         if(check_duplicate_type(strct))
1523                 return;
1524
1525         Id type_id = allocate_id(strct, 0);
1526         writer.write_op_name(type_id, strct.name);
1527
1528         if(strct.interface_block)
1529                 writer.write_op_decorate(type_id, DECO_BLOCK);
1530
1531         bool builtin = (strct.interface_block && !strct.interface_block->block_name.compare(0, 3, "gl_"));
1532         vector<Id> member_type_ids;
1533         member_type_ids.reserve(strct.members.body.size());
1534         for(const RefPtr<Statement> &s: strct.members.body)
1535         {
1536                 const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(s.get());
1537                 if(!var)
1538                         continue;
1539
1540                 unsigned index = member_type_ids.size();
1541                 member_type_ids.push_back(get_variable_type_id(*var));
1542
1543                 writer.write_op_member_name(type_id, index, var->name);
1544
1545                 if(builtin)
1546                 {
1547                         BuiltinSemantic semantic = get_builtin_semantic(var->name);
1548                         writer.write_op_member_decorate(type_id, index, DECO_BUILTIN, semantic);
1549                 }
1550                 else
1551                 {
1552                         if(var->layout)
1553                         {
1554                                 for(const Layout::Qualifier &q: var->layout->qualifiers)
1555                                 {
1556                                         if(q.name=="offset")
1557                                                 writer.write_op_member_decorate(type_id, index, DECO_OFFSET, q.value);
1558                                         else if(q.name=="column_major")
1559                                                 writer.write_op_member_decorate(type_id, index, DECO_COL_MAJOR);
1560                                         else if(q.name=="row_major")
1561                                                 writer.write_op_member_decorate(type_id, index, DECO_ROW_MAJOR);
1562                                 }
1563                         }
1564
1565                         const BasicTypeDeclaration *basic = dynamic_cast<const BasicTypeDeclaration *>(var->type_declaration);
1566                         while(basic && basic->kind==BasicTypeDeclaration::ARRAY)
1567                                 basic = dynamic_cast<const BasicTypeDeclaration *>(basic->base_type);
1568                         if(basic && basic->kind==BasicTypeDeclaration::MATRIX)
1569                         {
1570                                 unsigned stride = MemoryRequirementsCalculator().apply(*basic->base_type).stride;
1571                                 writer.write_op_member_decorate(type_id, index, DECO_MATRIX_STRIDE, stride);
1572                         }
1573                 }
1574         }
1575
1576         writer.begin_op(content.globals, OP_TYPE_STRUCT);
1577         writer.write(type_id);
1578         for(Id i: member_type_ids)
1579                 writer.write(i);
1580         writer.end_op(OP_TYPE_STRUCT);
1581 }
1582
1583 void SpirVGenerator::visit(VariableDeclaration &var)
1584 {
1585         Id type_id = get_variable_type_id(var);
1586         Id var_id;
1587
1588         if(var.constant)
1589         {
1590                 if(!var.init_expression)
1591                         throw internal_error("const variable without initializer");
1592
1593                 int spec_id = get_layout_value(var.layout.get(), "constant_id");
1594
1595                 SetFlag set_const(constant_expression);
1596                 SetFlag set_spec(spec_constant, spec_id>=0);
1597                 r_expression_result_id = 0;
1598                 var.init_expression->visit(*this);
1599                 var_id = r_expression_result_id;
1600                 insert_unique(declared_ids, &var, Declaration(var_id, type_id));
1601                 writer.write_op_decorate(var_id, DECO_SPEC_ID, spec_id);
1602
1603                 /* It's unclear what should be done if a specialization constant is
1604                 initialized with anything other than a literal.  GLSL doesn't seem to
1605                 prohibit that but SPIR-V says OpSpecConstantOp can't be updated via
1606                 specialization. */
1607         }
1608         else
1609         {
1610                 StorageClass storage = (current_function ? STORAGE_FUNCTION : get_interface_storage(var.interface, false));
1611                 Id ptr_type_id = get_pointer_type_id(type_id, storage);
1612                 if(var.interface=="uniform")
1613                 {
1614                         Id &uni_id = declared_uniform_ids["v"+var.name];
1615                         if(uni_id)
1616                         {
1617                                 insert_unique(declared_ids, &var, Declaration(uni_id, ptr_type_id));
1618                                 return;
1619                         }
1620
1621                         uni_id = var_id = allocate_id(var, ptr_type_id);
1622                 }
1623                 else
1624                         var_id = allocate_id(var, (var.constant ? type_id : ptr_type_id));
1625
1626                 Id init_id = 0;
1627                 if(var.init_expression)
1628                 {
1629                         SetFlag set_const(constant_expression, !current_function);
1630                         r_expression_result_id = 0;
1631                         r_constant_result = false;
1632                         var.init_expression->visit(*this);
1633                         init_id = r_expression_result_id;
1634                 }
1635
1636                 vector<Word> &target = (current_function ? content.locals : content.globals);
1637                 writer.begin_op(target, OP_VARIABLE, 4+(init_id && !current_function));
1638                 writer.write(ptr_type_id);
1639                 writer.write(var_id);
1640                 writer.write(storage);
1641                 if(init_id && !current_function)
1642                         writer.write(init_id);
1643                 writer.end_op(OP_VARIABLE);
1644
1645                 if(var.layout)
1646                 {
1647                         for(const Layout::Qualifier &q: var.layout->qualifiers)
1648                         {
1649                                 if(q.name=="location")
1650                                         writer.write_op_decorate(var_id, DECO_LOCATION, q.value);
1651                                 else if(q.name=="set")
1652                                         writer.write_op_decorate(var_id, DECO_DESCRIPTOR_SET, q.value);
1653                                 else if(q.name=="binding")
1654                                         writer.write_op_decorate(var_id, DECO_BINDING, q.value);
1655                         }
1656                 }
1657                 if(!var.name.compare(0, 3, "gl_"))
1658                 {
1659                         BuiltinSemantic semantic = get_builtin_semantic(var.name);
1660                         writer.write_op_decorate(var_id, DECO_BUILTIN, semantic);
1661                 }
1662
1663                 if(init_id && current_function)
1664                 {
1665                         writer.write_op(content.function_body, OP_STORE, var_id, init_id);
1666                         variable_load_ids[&var] = init_id;
1667                 }
1668         }
1669
1670         writer.write_op_name(var_id, var.name);
1671 }
1672
1673 void SpirVGenerator::visit(InterfaceBlock &iface)
1674 {
1675         bool push_const = has_layout_qualifier(iface.layout.get(), "push_constant");
1676
1677         StorageClass storage = (push_const ? STORAGE_PUSH_CONSTANT : get_interface_storage(iface.interface, true));
1678         Id type_id;
1679         if(iface.array)
1680                 type_id = get_array_type_id(*iface.struct_declaration, 0);
1681         else
1682                 type_id = get_id(*iface.struct_declaration);
1683         Id ptr_type_id = get_pointer_type_id(type_id, storage);
1684
1685         Id block_id;
1686         if(iface.interface=="uniform")
1687         {
1688                 Id &uni_id = declared_uniform_ids["b"+iface.block_name];
1689                 if(uni_id)
1690                 {
1691                         insert_unique(declared_ids, &iface, Declaration(uni_id, ptr_type_id));
1692                         return;
1693                 }
1694
1695                 uni_id = block_id = allocate_id(iface, ptr_type_id);
1696         }
1697         else
1698                 block_id = allocate_id(iface, ptr_type_id);
1699         writer.write_op_name(block_id, iface.instance_name);
1700
1701         writer.write_op(content.globals, OP_VARIABLE, ptr_type_id, block_id, storage);
1702
1703         if(iface.layout)
1704         {
1705                 for(const Layout::Qualifier &q: iface.layout->qualifiers)
1706                 {
1707                         if(q.name=="set")
1708                                 writer.write_op_decorate(block_id, DECO_DESCRIPTOR_SET, q.value);
1709                         else if(q.name=="binding")
1710                                 writer.write_op_decorate(block_id, DECO_BINDING, q.value);
1711                 }
1712         }
1713 }
1714
1715 void SpirVGenerator::visit_entry_point(FunctionDeclaration &func, Id func_id)
1716 {
1717         writer.begin_op(content.entry_points, OP_ENTRY_POINT);
1718         switch(stage->type)
1719         {
1720         case Stage::VERTEX: writer.write(0); break;
1721         case Stage::GEOMETRY: writer.write(3); break;
1722         case Stage::FRAGMENT: writer.write(4); break;
1723         default: throw internal_error("unknown stage");
1724         }
1725         writer.write(func_id);
1726         writer.write_string(func.name);
1727
1728         set<Node *> dependencies = DependencyCollector().apply(func);
1729         for(Node *n: dependencies)
1730         {
1731                 if(const VariableDeclaration *var = dynamic_cast<const VariableDeclaration *>(n))
1732                 {
1733                         if(!var->interface.empty())
1734                                 writer.write(get_id(*n));
1735                 }
1736                 else if(dynamic_cast<InterfaceBlock *>(n))
1737                         writer.write(get_id(*n));
1738         }
1739
1740         writer.end_op(OP_ENTRY_POINT);
1741
1742         if(stage->type==Stage::FRAGMENT)
1743                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_ORIGIN_LOWER_LEFT);
1744         else if(stage->type==Stage::GEOMETRY)
1745                 use_capability(CAP_GEOMETRY);
1746
1747         for(const InterfaceLayout *i: interface_layouts)
1748         {
1749                 for(const Layout::Qualifier &q: i->layout.qualifiers)
1750                 {
1751                         if(q.name=="point")
1752                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id,
1753                                         (i->interface=="in" ? EXEC_INPUT_POINTS : EXEC_OUTPUT_POINTS));
1754                         else if(q.name=="lines")
1755                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_LINES);
1756                         else if(q.name=="lines_adjacency")
1757                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_LINES_ADJACENCY);
1758                         else if(q.name=="triangles")
1759                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_TRIANGLES);
1760                         else if(q.name=="triangles_adjacency")
1761                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_INPUT_TRIANGLES_ADJACENCY);
1762                         else if(q.name=="line_strip")
1763                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_LINE_STRIP);
1764                         else if(q.name=="triangle_strip")
1765                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_TRIANGLE_STRIP);
1766                         else if(q.name=="max_vertices")
1767                                 writer.write_op(content.exec_modes, OP_EXECUTION_MODE, func_id, EXEC_OUTPUT_VERTICES, q.value);
1768                 }
1769         }
1770 }
1771
1772 void SpirVGenerator::visit(FunctionDeclaration &func)
1773 {
1774         if(func.source==BUILTIN_SOURCE)
1775                 return;
1776         else if(func.definition!=&func)
1777         {
1778                 if(func.definition)
1779                         allocate_forward_id(*func.definition);
1780                 return;
1781         }
1782
1783         Id return_type_id = get_id(*func.return_type_declaration);
1784         vector<unsigned> param_type_ids;
1785         param_type_ids.reserve(func.parameters.size());
1786         for(const RefPtr<VariableDeclaration> &p: func.parameters)
1787                 param_type_ids.push_back(get_variable_type_id(*p));
1788
1789         string sig_with_return = func.return_type+func.signature;
1790         Id &type_id = function_type_ids[sig_with_return];
1791         if(!type_id)
1792         {
1793                 type_id = next_id++;
1794                 writer.begin_op(content.globals, OP_TYPE_FUNCTION);
1795                 writer.write(type_id);
1796                 writer.write(return_type_id);
1797                 for(unsigned i: param_type_ids)
1798                         writer.write(i);
1799                 writer.end_op(OP_TYPE_FUNCTION);
1800
1801                 writer.write_op_name(type_id, sig_with_return);
1802         }
1803
1804         Id func_id = allocate_id(func, type_id);
1805         writer.write_op_name(func_id, func.name+func.signature);
1806
1807         if(func.name=="main")
1808                 visit_entry_point(func, func_id);
1809
1810         writer.begin_op(content.functions, OP_FUNCTION, 5);
1811         writer.write(return_type_id);
1812         writer.write(func_id);
1813         writer.write(0);  // Function control flags (none)
1814         writer.write(type_id);
1815         writer.end_op(OP_FUNCTION);
1816
1817         for(unsigned i=0; i<func.parameters.size(); ++i)
1818         {
1819                 Id param_id = allocate_id(*func.parameters[i], param_type_ids[i]);
1820                 writer.write_op(content.functions, OP_FUNCTION_PARAMETER, param_type_ids[i], param_id);
1821                 // TODO This is probably incorrect if the parameter is assigned to.
1822                 variable_load_ids[func.parameters[i].get()] = param_id;
1823         }
1824
1825         reachable = true;
1826         writer.begin_function_body(next_id++);
1827         SetForScope<FunctionDeclaration *> set_func(current_function, &func);
1828         func.body.visit(*this);
1829
1830         if(writer.get_current_block())
1831         {
1832                 if(!reachable)
1833                         writer.write_op(content.function_body, OP_UNREACHABLE);
1834                 else
1835                 {
1836                         const BasicTypeDeclaration *basic_return = dynamic_cast<const BasicTypeDeclaration *>(func.return_type_declaration);
1837                         if(basic_return && basic_return->kind==BasicTypeDeclaration::VOID)
1838                                 writer.write_op(content.function_body, OP_RETURN);
1839                         else
1840                                 throw internal_error("missing return in non-void function");
1841                 }
1842         }
1843         writer.end_function_body();
1844         variable_load_ids.clear();
1845 }
1846
1847 void SpirVGenerator::visit(Conditional &cond)
1848 {
1849         cond.condition->visit(*this);
1850
1851         Id true_label_id = next_id++;
1852         Id merge_block_id = next_id++;
1853         Id false_label_id = (cond.else_body.body.empty() ? merge_block_id : next_id++);
1854         writer.write_op(content.function_body, OP_SELECTION_MERGE, merge_block_id, 0);  // Selection control (none)
1855         writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, r_expression_result_id, true_label_id, false_label_id);
1856
1857         std::map<const VariableDeclaration *, Id> saved_load_ids = variable_load_ids;
1858
1859         writer.write_op_label(true_label_id);
1860         cond.body.visit(*this);
1861         if(writer.get_current_block())
1862                 writer.write_op(content.function_body, OP_BRANCH, merge_block_id);
1863
1864         bool reachable_if_true = reachable;
1865
1866         reachable = true;
1867         if(!cond.else_body.body.empty())
1868         {
1869                 swap(saved_load_ids, variable_load_ids);
1870                 writer.write_op_label(false_label_id);
1871                 cond.else_body.visit(*this);
1872                 reachable |= reachable_if_true;
1873         }
1874
1875         writer.write_op_label(merge_block_id);
1876         prune_loads(true_label_id);
1877 }
1878
1879 void SpirVGenerator::visit(Iteration &iter)
1880 {
1881         if(iter.init_statement)
1882                 iter.init_statement->visit(*this);
1883
1884         for(Node *n: AssignmentCollector().apply(iter))
1885                 if(VariableDeclaration *var = dynamic_cast<VariableDeclaration *>(n))
1886                         variable_load_ids.erase(var);
1887
1888         Id header_id = next_id++;
1889         Id continue_id = next_id++;
1890         Id merge_block_id = next_id++;
1891
1892         SetForScope<Id> set_merge(loop_merge_block_id, merge_block_id);
1893         SetForScope<Id> set_continue(loop_continue_target_id, continue_id);
1894
1895         writer.write_op_label(header_id);
1896         writer.write_op(content.function_body, OP_LOOP_MERGE, merge_block_id, continue_id, 0);  // Loop control (none)
1897
1898         Id body_id = next_id++;
1899         if(iter.condition)
1900         {
1901                 writer.write_op_label(next_id++);
1902                 iter.condition->visit(*this);
1903                 writer.write_op(content.function_body, OP_BRANCH_CONDITIONAL, r_expression_result_id, body_id, merge_block_id);
1904         }
1905
1906         writer.write_op_label(body_id);
1907         iter.body.visit(*this);
1908
1909         writer.write_op_label(continue_id);
1910         if(iter.loop_expression)
1911                 iter.loop_expression->visit(*this);
1912         writer.write_op(content.function_body, OP_BRANCH, header_id);
1913
1914         writer.write_op_label(merge_block_id);
1915         prune_loads(header_id);
1916         reachable = true;
1917 }
1918
1919 void SpirVGenerator::visit(Return &ret)
1920 {
1921         if(ret.expression)
1922         {
1923                 ret.expression->visit(*this);
1924                 writer.write_op(content.function_body, OP_RETURN_VALUE, r_expression_result_id);
1925         }
1926         else
1927                 writer.write_op(content.function_body, OP_RETURN);
1928         reachable = false;
1929 }
1930
1931 void SpirVGenerator::visit(Jump &jump)
1932 {
1933         if(jump.keyword=="discard")
1934                 writer.write_op(content.function_body, OP_KILL);
1935         else if(jump.keyword=="break")
1936                 writer.write_op(content.function_body, OP_BRANCH, loop_merge_block_id);
1937         else if(jump.keyword=="continue")
1938                 writer.write_op(content.function_body, OP_BRANCH, loop_continue_target_id);
1939         else
1940                 throw internal_error("unknown jump");
1941         reachable = false;
1942 }
1943
1944
1945 SpirVGenerator::TypeKey::TypeKey(BasicTypeDeclaration::Kind kind, bool sign):
1946         type_id(0)
1947 {
1948         switch(kind)
1949         {
1950         case BasicTypeDeclaration::VOID: detail = 'v'; break;
1951         case BasicTypeDeclaration::BOOL: detail = 'b'; break;
1952         case BasicTypeDeclaration::INT: detail = (sign ? 'i' : 'u'); break;
1953         case BasicTypeDeclaration::FLOAT: detail = 'f'; break;
1954         default: throw invalid_argument("TypeKey::TypeKey");
1955         }
1956 }
1957
1958 bool SpirVGenerator::TypeKey::operator<(const TypeKey &other) const
1959 {
1960         if(type_id!=other.type_id)
1961                 return type_id<other.type_id;
1962         return detail<other.detail;
1963 }
1964
1965
1966 bool SpirVGenerator::ConstantKey::operator<(const ConstantKey &other) const
1967 {
1968         if(type_id!=other.type_id)
1969                 return type_id<other.type_id;
1970         return int_value<other.int_value;
1971 }
1972
1973 } // namespace SL
1974 } // namespace GL
1975 } // namespace Msp