blob: 1c0a830f233dddc6fed7b47bccde64083c8fdac5 [file] [log] [blame]
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001/*
Hans-Kristian Arntzen318c17c2019-01-04 12:38:35 +01002 * Copyright 2018-2019 Arm Limited
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "spirv_parser.hpp"
18#include <assert.h>
19
20using namespace std;
21using namespace spv;
22
Hans-Kristian Arntzen9b92e682019-03-29 10:29:44 +010023namespace SPIRV_CROSS_NAMESPACE
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020024{
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +020025Parser::Parser(vector<uint32_t> spirv)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020026{
27 ir.spirv = move(spirv);
28}
29
30Parser::Parser(const uint32_t *spirv_data, size_t word_count)
31{
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +020032 ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020033}
34
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +010035static bool decoration_is_string(Decoration decoration)
36{
37 switch (decoration)
38 {
39 case DecorationHlslSemanticGOOGLE:
40 return true;
41
42 default:
43 return false;
44 }
45}
46
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020047static inline uint32_t swap_endian(uint32_t v)
48{
49 return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
50}
51
52static bool is_valid_spirv_version(uint32_t version)
53{
54 switch (version)
55 {
56 // Allow v99 since it tends to just work.
57 case 99:
58 case 0x10000: // SPIR-V 1.0
59 case 0x10100: // SPIR-V 1.1
60 case 0x10200: // SPIR-V 1.2
61 case 0x10300: // SPIR-V 1.3
Hans-Kristian Arntzenab1fa902019-05-07 09:53:40 +020062 case 0x10400: // SPIR-V 1.4
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020063 return true;
64
65 default:
66 return false;
67 }
68}
69
70void Parser::parse()
71{
72 auto &spirv = ir.spirv;
73
74 auto len = spirv.size();
75 if (len < 5)
76 SPIRV_CROSS_THROW("SPIRV file too small.");
77
78 auto s = spirv.data();
79
80 // Endian-swap if we need to.
81 if (s[0] == swap_endian(MagicNumber))
82 transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
83
84 if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
85 SPIRV_CROSS_THROW("Invalid SPIRV format.");
86
87 uint32_t bound = s[3];
88 ir.set_id_bounds(bound);
89
90 uint32_t offset = 5;
91
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020092 SmallVector<Instruction> instructions;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020093 while (offset < len)
94 {
95 Instruction instr = {};
96 instr.op = spirv[offset] & 0xffff;
97 instr.count = (spirv[offset] >> 16) & 0xffff;
98
99 if (instr.count == 0)
100 SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
101
102 instr.offset = offset + 1;
103 instr.length = instr.count - 1;
104
105 offset += instr.count;
106
107 if (offset > spirv.size())
108 SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
109
110 instructions.push_back(instr);
111 }
112
113 for (auto &i : instructions)
114 parse(i);
115
116 if (current_function)
117 SPIRV_CROSS_THROW("Function was not terminated.");
118 if (current_block)
119 SPIRV_CROSS_THROW("Block was not terminated.");
120}
121
122const uint32_t *Parser::stream(const Instruction &instr) const
123{
124 // If we're not going to use any arguments, just return nullptr.
125 // We want to avoid case where we return an out of range pointer
126 // that trips debug assertions on some platforms.
127 if (!instr.length)
128 return nullptr;
129
130 if (instr.offset + instr.length > ir.spirv.size())
131 SPIRV_CROSS_THROW("Compiler::stream() out of range.");
132 return &ir.spirv[instr.offset];
133}
134
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +0200135static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200136{
137 string ret;
138 for (uint32_t i = offset; i < spirv.size(); i++)
139 {
140 uint32_t w = spirv[i];
141
142 for (uint32_t j = 0; j < 4; j++, w >>= 8)
143 {
144 char c = w & 0xff;
145 if (c == '\0')
146 return ret;
147 ret += c;
148 }
149 }
150
151 SPIRV_CROSS_THROW("String was not terminated before EOF");
152}
153
154void Parser::parse(const Instruction &instruction)
155{
156 auto *ops = stream(instruction);
157 auto op = static_cast<Op>(instruction.op);
158 uint32_t length = instruction.length;
159
160 switch (op)
161 {
lifpan00a765e2018-11-15 09:04:36 +0800162 case OpSourceContinued:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200163 case OpSourceExtension:
164 case OpNop:
165 case OpLine:
166 case OpNoLine:
167 case OpString:
lifpan91610962018-11-13 14:28:38 +0800168 case OpModuleProcessed:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200169 break;
170
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200171 case OpMemoryModel:
172 ir.addressing_model = static_cast<AddressingModel>(ops[0]);
173 ir.memory_model = static_cast<MemoryModel>(ops[1]);
174 break;
175
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200176 case OpSource:
177 {
178 auto lang = static_cast<SourceLanguage>(ops[0]);
179 switch (lang)
180 {
181 case SourceLanguageESSL:
182 ir.source.es = true;
183 ir.source.version = ops[1];
184 ir.source.known = true;
185 ir.source.hlsl = false;
186 break;
187
188 case SourceLanguageGLSL:
189 ir.source.es = false;
190 ir.source.version = ops[1];
191 ir.source.known = true;
192 ir.source.hlsl = false;
193 break;
194
195 case SourceLanguageHLSL:
196 // For purposes of cross-compiling, this is GLSL 450.
197 ir.source.es = false;
198 ir.source.version = 450;
199 ir.source.known = true;
200 ir.source.hlsl = true;
201 break;
202
203 default:
204 ir.source.known = false;
205 break;
206 }
207 break;
208 }
209
210 case OpUndef:
211 {
212 uint32_t result_type = ops[0];
213 uint32_t id = ops[1];
214 set<SPIRUndef>(id, result_type);
lifpan876627d2019-04-08 19:45:31 +0800215 if (current_block)
216 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200217 break;
218 }
219
220 case OpCapability:
221 {
222 uint32_t cap = ops[0];
223 if (cap == CapabilityKernel)
224 SPIRV_CROSS_THROW("Kernel capability not supported.");
225
226 ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
227 break;
228 }
229
230 case OpExtension:
231 {
232 auto ext = extract_string(ir.spirv, instruction.offset);
233 ir.declared_extensions.push_back(move(ext));
234 break;
235 }
236
237 case OpExtInstImport:
238 {
239 uint32_t id = ops[0];
240 auto ext = extract_string(ir.spirv, instruction.offset + 1);
241 if (ext == "GLSL.std.450")
242 set<SPIRExtension>(id, SPIRExtension::GLSL);
243 else if (ext == "SPV_AMD_shader_ballot")
244 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
245 else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
246 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
247 else if (ext == "SPV_AMD_shader_trinary_minmax")
248 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
249 else if (ext == "SPV_AMD_gcn_shader")
250 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
251 else
252 set<SPIRExtension>(id, SPIRExtension::Unsupported);
253
254 // Other SPIR-V extensions which have ExtInstrs are currently not supported.
255
256 break;
257 }
258
259 case OpEntryPoint:
260 {
261 auto itr =
262 ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
263 extract_string(ir.spirv, instruction.offset + 2))));
264 auto &e = itr.first->second;
265
266 // Strings need nul-terminator and consume the whole word.
267 uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
268 e.interface_variables.insert(end(e.interface_variables), ops + strlen_words + 2, ops + instruction.length);
269
270 // Set the name of the entry point in case OpName is not provided later.
271 ir.set_name(ops[1], e.name);
272
273 // If we don't have an entry, make the first one our "default".
274 if (!ir.default_entry_point)
275 ir.default_entry_point = ops[1];
276 break;
277 }
278
279 case OpExecutionMode:
280 {
281 auto &execution = ir.entry_points[ops[0]];
282 auto mode = static_cast<ExecutionMode>(ops[1]);
283 execution.flags.set(mode);
284
285 switch (mode)
286 {
287 case ExecutionModeInvocations:
288 execution.invocations = ops[2];
289 break;
290
291 case ExecutionModeLocalSize:
292 execution.workgroup_size.x = ops[2];
293 execution.workgroup_size.y = ops[3];
294 execution.workgroup_size.z = ops[4];
295 break;
296
297 case ExecutionModeOutputVertices:
298 execution.output_vertices = ops[2];
299 break;
300
301 default:
302 break;
303 }
304 break;
305 }
306
307 case OpName:
308 {
309 uint32_t id = ops[0];
310 ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
311 break;
312 }
313
314 case OpMemberName:
315 {
316 uint32_t id = ops[0];
317 uint32_t member = ops[1];
318 ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
319 break;
320 }
321
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100322 case OpDecorationGroup:
323 {
324 // Noop, this simply means an ID should be a collector of decorations.
325 // The meta array is already a flat array of decorations which will contain the relevant decorations.
326 break;
327 }
328
329 case OpGroupDecorate:
330 {
331 uint32_t group_id = ops[0];
332 auto &decorations = ir.meta[group_id].decoration;
333 auto &flags = decorations.decoration_flags;
334
335 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
336 // i.e., we cannot just copy the meta structure directly.
337 for (uint32_t i = 1; i < length; i++)
338 {
339 uint32_t target = ops[i];
340 flags.for_each_bit([&](uint32_t bit) {
341 auto decoration = static_cast<Decoration>(bit);
342
343 if (decoration_is_string(decoration))
344 {
345 ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
346 }
347 else
348 {
349 ir.meta[target].decoration_word_offset[decoration] =
350 ir.meta[group_id].decoration_word_offset[decoration];
351 ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
352 }
353 });
354 }
355 break;
356 }
357
358 case OpGroupMemberDecorate:
359 {
360 uint32_t group_id = ops[0];
361 auto &flags = ir.meta[group_id].decoration.decoration_flags;
362
363 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
364 // i.e., we cannot just copy the meta structure directly.
365 for (uint32_t i = 1; i + 1 < length; i += 2)
366 {
367 uint32_t target = ops[i + 0];
368 uint32_t index = ops[i + 1];
369 flags.for_each_bit([&](uint32_t bit) {
370 auto decoration = static_cast<Decoration>(bit);
371
372 if (decoration_is_string(decoration))
373 ir.set_member_decoration_string(target, index, decoration,
374 ir.get_decoration_string(group_id, decoration));
375 else
376 ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
377 });
378 }
379 break;
380 }
381
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200382 case OpDecorate:
383 case OpDecorateId:
384 {
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100385 // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
386 // so merge decorate and decorate-id here.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200387 uint32_t id = ops[0];
388
389 auto decoration = static_cast<Decoration>(ops[1]);
390 if (length >= 3)
391 {
392 ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
393 ir.set_decoration(id, decoration, ops[2]);
394 }
395 else
396 ir.set_decoration(id, decoration);
397
398 break;
399 }
400
401 case OpDecorateStringGOOGLE:
402 {
403 uint32_t id = ops[0];
404 auto decoration = static_cast<Decoration>(ops[1]);
405 ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
406 break;
407 }
408
409 case OpMemberDecorate:
410 {
411 uint32_t id = ops[0];
412 uint32_t member = ops[1];
413 auto decoration = static_cast<Decoration>(ops[2]);
414 if (length >= 4)
415 ir.set_member_decoration(id, member, decoration, ops[3]);
416 else
417 ir.set_member_decoration(id, member, decoration);
418 break;
419 }
420
421 case OpMemberDecorateStringGOOGLE:
422 {
423 uint32_t id = ops[0];
424 uint32_t member = ops[1];
425 auto decoration = static_cast<Decoration>(ops[2]);
426 ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
427 break;
428 }
429
430 // Build up basic types.
431 case OpTypeVoid:
432 {
433 uint32_t id = ops[0];
434 auto &type = set<SPIRType>(id);
435 type.basetype = SPIRType::Void;
436 break;
437 }
438
439 case OpTypeBool:
440 {
441 uint32_t id = ops[0];
442 auto &type = set<SPIRType>(id);
443 type.basetype = SPIRType::Boolean;
444 type.width = 1;
445 break;
446 }
447
448 case OpTypeFloat:
449 {
450 uint32_t id = ops[0];
451 uint32_t width = ops[1];
452 auto &type = set<SPIRType>(id);
453 if (width == 64)
454 type.basetype = SPIRType::Double;
455 else if (width == 32)
456 type.basetype = SPIRType::Float;
457 else if (width == 16)
458 type.basetype = SPIRType::Half;
459 else
460 SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
461 type.width = width;
462 break;
463 }
464
465 case OpTypeInt:
466 {
467 uint32_t id = ops[0];
468 uint32_t width = ops[1];
lifpanb21525b2018-11-28 14:20:24 +0800469 bool signedness = ops[2] != 0;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200470 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +0100471 type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200472 type.width = width;
473 break;
474 }
475
476 // Build composite types by "inheriting".
477 // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
478 // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
479 case OpTypeVector:
480 {
481 uint32_t id = ops[0];
482 uint32_t vecsize = ops[2];
483
484 auto &base = get<SPIRType>(ops[1]);
485 auto &vecbase = set<SPIRType>(id);
486
487 vecbase = base;
488 vecbase.vecsize = vecsize;
489 vecbase.self = id;
490 vecbase.parent_type = ops[1];
491 break;
492 }
493
494 case OpTypeMatrix:
495 {
496 uint32_t id = ops[0];
497 uint32_t colcount = ops[2];
498
499 auto &base = get<SPIRType>(ops[1]);
500 auto &matrixbase = set<SPIRType>(id);
501
502 matrixbase = base;
503 matrixbase.columns = colcount;
504 matrixbase.self = id;
505 matrixbase.parent_type = ops[1];
506 break;
507 }
508
509 case OpTypeArray:
510 {
511 uint32_t id = ops[0];
512 auto &arraybase = set<SPIRType>(id);
513
514 uint32_t tid = ops[1];
515 auto &base = get<SPIRType>(tid);
516
517 arraybase = base;
518 arraybase.parent_type = tid;
519
520 uint32_t cid = ops[2];
521 ir.mark_used_as_array_length(cid);
522 auto *c = maybe_get<SPIRConstant>(cid);
523 bool literal = c && !c->specialization;
524
525 arraybase.array_size_literal.push_back(literal);
526 arraybase.array.push_back(literal ? c->scalar() : cid);
527 // Do NOT set arraybase.self!
528 break;
529 }
530
531 case OpTypeRuntimeArray:
532 {
533 uint32_t id = ops[0];
534
535 auto &base = get<SPIRType>(ops[1]);
536 auto &arraybase = set<SPIRType>(id);
537
538 arraybase = base;
539 arraybase.array.push_back(0);
540 arraybase.array_size_literal.push_back(true);
541 arraybase.parent_type = ops[1];
542 // Do NOT set arraybase.self!
543 break;
544 }
545
546 case OpTypeImage:
547 {
548 uint32_t id = ops[0];
549 auto &type = set<SPIRType>(id);
550 type.basetype = SPIRType::Image;
551 type.image.type = ops[1];
552 type.image.dim = static_cast<Dim>(ops[2]);
553 type.image.depth = ops[3] == 1;
554 type.image.arrayed = ops[4] != 0;
555 type.image.ms = ops[5] != 0;
556 type.image.sampled = ops[6];
557 type.image.format = static_cast<ImageFormat>(ops[7]);
558 type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
559
560 if (type.image.sampled == 0)
561 SPIRV_CROSS_THROW("OpTypeImage Sampled parameter must not be zero.");
562
563 break;
564 }
565
566 case OpTypeSampledImage:
567 {
568 uint32_t id = ops[0];
569 uint32_t imagetype = ops[1];
570 auto &type = set<SPIRType>(id);
571 type = get<SPIRType>(imagetype);
572 type.basetype = SPIRType::SampledImage;
573 type.self = id;
574 break;
575 }
576
577 case OpTypeSampler:
578 {
579 uint32_t id = ops[0];
580 auto &type = set<SPIRType>(id);
581 type.basetype = SPIRType::Sampler;
582 break;
583 }
584
585 case OpTypePointer:
586 {
587 uint32_t id = ops[0];
588
589 auto &base = get<SPIRType>(ops[2]);
590 auto &ptrbase = set<SPIRType>(id);
591
592 ptrbase = base;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200593 ptrbase.pointer = true;
Hans-Kristian Arntzend0b93722018-11-26 12:23:28 +0100594 ptrbase.pointer_depth++;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200595 ptrbase.storage = static_cast<StorageClass>(ops[1]);
596
597 if (ptrbase.storage == StorageClassAtomicCounter)
598 ptrbase.basetype = SPIRType::AtomicCounter;
599
600 ptrbase.parent_type = ops[2];
601
602 // Do NOT set ptrbase.self!
603 break;
604 }
605
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200606 case OpTypeForwardPointer:
607 {
608 uint32_t id = ops[0];
609 auto &ptrbase = set<SPIRType>(id);
610 ptrbase.pointer = true;
611 ptrbase.pointer_depth++;
612 ptrbase.storage = static_cast<StorageClass>(ops[1]);
613
614 if (ptrbase.storage == StorageClassAtomicCounter)
615 ptrbase.basetype = SPIRType::AtomicCounter;
616
617 break;
618 }
619
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200620 case OpTypeStruct:
621 {
622 uint32_t id = ops[0];
623 auto &type = set<SPIRType>(id);
624 type.basetype = SPIRType::Struct;
625 for (uint32_t i = 1; i < length; i++)
626 type.member_types.push_back(ops[i]);
627
628 // Check if we have seen this struct type before, with just different
629 // decorations.
630 //
631 // Add workaround for issue #17 as well by looking at OpName for the struct
632 // types, which we shouldn't normally do.
633 // We should not normally have to consider type aliases like this to begin with
634 // however ... glslang issues #304, #307 cover this.
635
636 // For stripped names, never consider struct type aliasing.
637 // We risk declaring the same struct multiple times, but type-punning is not allowed
638 // so this is safe.
639 bool consider_aliasing = !ir.get_name(type.self).empty();
640 if (consider_aliasing)
641 {
642 for (auto &other : global_struct_cache)
643 {
644 if (ir.get_name(type.self) == ir.get_name(other) &&
645 types_are_logically_equivalent(type, get<SPIRType>(other)))
646 {
647 type.type_alias = other;
648 break;
649 }
650 }
651
652 if (type.type_alias == 0)
653 global_struct_cache.push_back(id);
654 }
655 break;
656 }
657
658 case OpTypeFunction:
659 {
660 uint32_t id = ops[0];
661 uint32_t ret = ops[1];
662
663 auto &func = set<SPIRFunctionPrototype>(id, ret);
664 for (uint32_t i = 2; i < length; i++)
665 func.parameter_types.push_back(ops[i]);
666 break;
667 }
668
Patrick Moursda39a7b2019-02-26 15:43:03 +0100669 case OpTypeAccelerationStructureNV:
670 {
671 uint32_t id = ops[0];
672 auto &type = set<SPIRType>(id);
673 type.basetype = SPIRType::AccelerationStructureNV;
674 break;
675 }
676
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200677 // Variable declaration
678 // All variables are essentially pointers with a storage qualifier.
679 case OpVariable:
680 {
681 uint32_t type = ops[0];
682 uint32_t id = ops[1];
683 auto storage = static_cast<StorageClass>(ops[2]);
684 uint32_t initializer = length == 4 ? ops[3] : 0;
685
686 if (storage == StorageClassFunction)
687 {
688 if (!current_function)
689 SPIRV_CROSS_THROW("No function currently in scope");
690 current_function->add_local_variable(id);
691 }
692
693 set<SPIRVariable>(id, type, storage, initializer);
694
695 // hlsl based shaders don't have those decorations. force them and then reset when reading/writing images
696 auto &ttype = get<SPIRType>(type);
697 if (ttype.basetype == SPIRType::BaseType::Image)
698 {
699 ir.set_decoration(id, DecorationNonWritable);
700 ir.set_decoration(id, DecorationNonReadable);
701 }
702
703 break;
704 }
705
706 // OpPhi
707 // OpPhi is a fairly magical opcode.
708 // It selects temporary variables based on which parent block we *came from*.
709 // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
710 // variable to emulate SSA Phi.
711 case OpPhi:
712 {
713 if (!current_function)
714 SPIRV_CROSS_THROW("No function currently in scope");
715 if (!current_block)
716 SPIRV_CROSS_THROW("No block currently in scope");
717
718 uint32_t result_type = ops[0];
719 uint32_t id = ops[1];
720
721 // Instead of a temporary, create a new function-wide temporary with this ID instead.
722 auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
723 var.phi_variable = true;
724
725 current_function->add_local_variable(id);
726
727 for (uint32_t i = 2; i + 2 <= length; i += 2)
728 current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
729 break;
730 }
731
732 // Constants
733 case OpSpecConstant:
734 case OpConstant:
735 {
736 uint32_t id = ops[1];
737 auto &type = get<SPIRType>(ops[0]);
738
739 if (type.width > 32)
740 set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
741 else
742 set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
743 break;
744 }
745
746 case OpSpecConstantFalse:
747 case OpConstantFalse:
748 {
749 uint32_t id = ops[1];
750 set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
751 break;
752 }
753
754 case OpSpecConstantTrue:
755 case OpConstantTrue:
756 {
757 uint32_t id = ops[1];
758 set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
759 break;
760 }
761
762 case OpConstantNull:
763 {
764 uint32_t id = ops[1];
765 uint32_t type = ops[0];
766 make_constant_null(id, type);
767 break;
768 }
769
770 case OpSpecConstantComposite:
771 case OpConstantComposite:
772 {
773 uint32_t id = ops[1];
774 uint32_t type = ops[0];
775
776 auto &ctype = get<SPIRType>(type);
777
778 // We can have constants which are structs and arrays.
779 // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
780 // can refer to.
781 if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
782 {
783 set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
784 }
785 else
786 {
787 uint32_t elements = length - 2;
788 if (elements > 4)
789 SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
790
791 SPIRConstant remapped_constant_ops[4];
792 const SPIRConstant *c[4];
793 for (uint32_t i = 0; i < elements; i++)
794 {
795 // Specialization constants operations can also be part of this.
796 // We do not know their value, so any attempt to query SPIRConstant later
797 // will fail. We can only propagate the ID of the expression and use to_expression on it.
798 auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100799 auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200800 if (constant_op)
801 {
802 if (op == OpConstantComposite)
803 SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
804
805 remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
806 remapped_constant_ops[i].self = constant_op->self;
807 remapped_constant_ops[i].constant_type = constant_op->basetype;
808 remapped_constant_ops[i].specialization = true;
809 c[i] = &remapped_constant_ops[i];
810 }
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100811 else if (undef_op)
812 {
813 // Undefined, just pick 0.
814 remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
815 remapped_constant_ops[i].constant_type = undef_op->basetype;
816 c[i] = &remapped_constant_ops[i];
817 }
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200818 else
819 c[i] = &get<SPIRConstant>(ops[2 + i]);
820 }
821 set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
822 }
823 break;
824 }
825
826 // Functions
827 case OpFunction:
828 {
829 uint32_t res = ops[0];
830 uint32_t id = ops[1];
831 // Control
832 uint32_t type = ops[3];
833
834 if (current_function)
835 SPIRV_CROSS_THROW("Must end a function before starting a new one!");
836
837 current_function = &set<SPIRFunction>(id, res, type);
838 break;
839 }
840
841 case OpFunctionParameter:
842 {
843 uint32_t type = ops[0];
844 uint32_t id = ops[1];
845
846 if (!current_function)
847 SPIRV_CROSS_THROW("Must be in a function!");
848
849 current_function->add_parameter(type, id);
850 set<SPIRVariable>(id, type, StorageClassFunction);
851 break;
852 }
853
854 case OpFunctionEnd:
855 {
856 if (current_block)
857 {
858 // Very specific error message, but seems to come up quite often.
859 SPIRV_CROSS_THROW(
860 "Cannot end a function before ending the current block.\n"
861 "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
862 }
863 current_function = nullptr;
864 break;
865 }
866
867 // Blocks
868 case OpLabel:
869 {
870 // OpLabel always starts a block.
871 if (!current_function)
872 SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
873
874 uint32_t id = ops[0];
875
876 current_function->blocks.push_back(id);
877 if (!current_function->entry_block)
878 current_function->entry_block = id;
879
880 if (current_block)
881 SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
882
883 current_block = &set<SPIRBlock>(id);
884 break;
885 }
886
887 // Branch instructions end blocks.
888 case OpBranch:
889 {
890 if (!current_block)
891 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
892
893 uint32_t target = ops[0];
894 current_block->terminator = SPIRBlock::Direct;
895 current_block->next_block = target;
896 current_block = nullptr;
897 break;
898 }
899
900 case OpBranchConditional:
901 {
902 if (!current_block)
903 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
904
905 current_block->condition = ops[0];
906 current_block->true_block = ops[1];
907 current_block->false_block = ops[2];
908
909 current_block->terminator = SPIRBlock::Select;
910 current_block = nullptr;
911 break;
912 }
913
914 case OpSwitch:
915 {
916 if (!current_block)
917 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
918
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200919 current_block->terminator = SPIRBlock::MultiSelect;
920
921 current_block->condition = ops[0];
922 current_block->default_block = ops[1];
923
924 for (uint32_t i = 2; i + 2 <= length; i += 2)
925 current_block->cases.push_back({ ops[i], ops[i + 1] });
926
927 // If we jump to next block, make it break instead since we're inside a switch case block at that point.
928 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
929
930 current_block = nullptr;
931 break;
932 }
933
934 case OpKill:
935 {
936 if (!current_block)
937 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
938 current_block->terminator = SPIRBlock::Kill;
939 current_block = nullptr;
940 break;
941 }
942
943 case OpReturn:
944 {
945 if (!current_block)
946 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
947 current_block->terminator = SPIRBlock::Return;
948 current_block = nullptr;
949 break;
950 }
951
952 case OpReturnValue:
953 {
954 if (!current_block)
955 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
956 current_block->terminator = SPIRBlock::Return;
957 current_block->return_value = ops[0];
958 current_block = nullptr;
959 break;
960 }
961
962 case OpUnreachable:
963 {
964 if (!current_block)
965 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
966 current_block->terminator = SPIRBlock::Unreachable;
967 current_block = nullptr;
968 break;
969 }
970
971 case OpSelectionMerge:
972 {
973 if (!current_block)
974 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
975
976 current_block->next_block = ops[0];
977 current_block->merge = SPIRBlock::MergeSelection;
978 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
979
980 if (length >= 2)
981 {
982 if (ops[1] & SelectionControlFlattenMask)
983 current_block->hint = SPIRBlock::HintFlatten;
984 else if (ops[1] & SelectionControlDontFlattenMask)
985 current_block->hint = SPIRBlock::HintDontFlatten;
986 }
987 break;
988 }
989
990 case OpLoopMerge:
991 {
992 if (!current_block)
993 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
994
995 current_block->merge_block = ops[0];
996 current_block->continue_block = ops[1];
997 current_block->merge = SPIRBlock::MergeLoop;
998
999 ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
1000 ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1001
1002 ir.continue_block_to_loop_header[current_block->continue_block] = current_block->self;
1003
1004 // Don't add loop headers to continue blocks,
1005 // which would make it impossible branch into the loop header since
1006 // they are treated as continues.
1007 if (current_block->continue_block != current_block->self)
1008 ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
1009
1010 if (length >= 3)
1011 {
1012 if (ops[2] & LoopControlUnrollMask)
1013 current_block->hint = SPIRBlock::HintUnroll;
1014 else if (ops[2] & LoopControlDontUnrollMask)
1015 current_block->hint = SPIRBlock::HintDontUnroll;
1016 }
1017 break;
1018 }
1019
1020 case OpSpecConstantOp:
1021 {
1022 if (length < 3)
1023 SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
1024
1025 uint32_t result_type = ops[0];
1026 uint32_t id = ops[1];
1027 auto spec_op = static_cast<Op>(ops[2]);
1028
1029 set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
1030 break;
1031 }
1032
1033 // Actual opcodes.
1034 default:
1035 {
1036 if (!current_block)
1037 SPIRV_CROSS_THROW("Currently no block to insert opcode.");
1038
1039 current_block->ops.push_back(instruction);
1040 break;
1041 }
1042 }
1043}
1044
1045bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
1046{
1047 if (a.basetype != b.basetype)
1048 return false;
1049 if (a.width != b.width)
1050 return false;
1051 if (a.vecsize != b.vecsize)
1052 return false;
1053 if (a.columns != b.columns)
1054 return false;
1055 if (a.array.size() != b.array.size())
1056 return false;
1057
1058 size_t array_count = a.array.size();
1059 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
1060 return false;
1061
1062 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
1063 {
1064 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
1065 return false;
1066 }
1067
1068 if (a.member_types.size() != b.member_types.size())
1069 return false;
1070
1071 size_t member_types = a.member_types.size();
1072 for (size_t i = 0; i < member_types; i++)
1073 {
1074 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
1075 return false;
1076 }
1077
1078 return true;
1079}
1080
1081bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
1082{
1083 auto &type = get<SPIRType>(v.basetype);
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001084
1085 auto *type_meta = ir.find_meta(type.self);
1086
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001087 bool ssbo = v.storage == StorageClassStorageBuffer ||
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001088 (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001089 bool image = type.basetype == SPIRType::Image;
1090 bool counter = type.basetype == SPIRType::AtomicCounter;
1091
1092 bool is_restrict;
1093 if (ssbo)
1094 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
1095 else
1096 is_restrict = ir.has_decoration(v.self, DecorationRestrict);
1097
1098 return !is_restrict && (ssbo || image || counter);
1099}
1100
1101void Parser::make_constant_null(uint32_t id, uint32_t type)
1102{
1103 auto &constant_type = get<SPIRType>(type);
1104
Chip Davis3bfb2f92018-12-03 02:06:33 -06001105 if (constant_type.pointer)
1106 {
1107 auto &constant = set<SPIRConstant>(id, type);
1108 constant.make_null(constant_type);
1109 }
1110 else if (!constant_type.array.empty())
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001111 {
1112 assert(constant_type.parent_type);
1113 uint32_t parent_id = ir.increase_bound_by(1);
1114 make_constant_null(parent_id, constant_type.parent_type);
1115
1116 if (!constant_type.array_size_literal.back())
1117 SPIRV_CROSS_THROW("Array size of OpConstantNull must be a literal.");
1118
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001119 SmallVector<uint32_t> elements(constant_type.array.back());
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001120 for (uint32_t i = 0; i < constant_type.array.back(); i++)
1121 elements[i] = parent_id;
1122 set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
1123 }
1124 else if (!constant_type.member_types.empty())
1125 {
1126 uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001127 SmallVector<uint32_t> elements(constant_type.member_types.size());
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001128 for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
1129 {
1130 make_constant_null(member_ids + i, constant_type.member_types[i]);
1131 elements[i] = member_ids + i;
1132 }
1133 set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
1134 }
1135 else
1136 {
1137 auto &constant = set<SPIRConstant>(id, type);
1138 constant.make_null(constant_type);
1139 }
1140}
1141
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001142} // namespace SPIRV_CROSS_NAMESPACE