Debian Codegraph @

thirdparty/spirv-cross/spirv_parser.cpp

raw symbols SCIP
1 /*
2 * Copyright 2018-2021 Arm Limited
3 * SPDX-License-Identifier: Apache-2.0 OR MIT
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 * At your option, you may choose to accept this material under either:
20 * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
21 * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
22 */
23
24 #include "spirv_parser.hpp"
25 #include <assert.h>
26
27 using namespace std;
28 using namespace spv;
29
30 namespace SPIRV_CROSS_NAMESPACE
31 {
32 Parser::Parser(vector<uint32_t> spirv)
33 {
34 ir.spirv = std::move(spirv);
35 }
36
37 Parser::Parser(const uint32_t *spirv_data, size_t word_count)
38 {
39 ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
40 }
41
42 static bool decoration_is_string(Decoration decoration)
43 {
44 switch (decoration)
45 {
46 case DecorationHlslSemanticGOOGLE:
47 return true;
48
49 default:
50 return false;
51 }
52 }
53
54 static inline uint32_t swap_endian(uint32_t v)
55 {
56 return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
57 }
58
59 static bool is_valid_spirv_version(uint32_t version)
60 {
61 switch (version)
62 {
63 // Allow v99 since it tends to just work.
64 case 99:
65 case 0x10000: // SPIR-V 1.0
66 case 0x10100: // SPIR-V 1.1
67 case 0x10200: // SPIR-V 1.2
68 case 0x10300: // SPIR-V 1.3
69 case 0x10400: // SPIR-V 1.4
70 case 0x10500: // SPIR-V 1.5
71 case 0x10600: // SPIR-V 1.6
72 return true;
73
74 default:
75 return false;
76 }
77 }
78
79 void Parser::parse()
80 {
81 auto &spirv = ir.spirv;
82
83 auto len = spirv.size();
84 if (len < 5)
85 SPIRV_CROSS_THROW("SPIRV file too small.");
86
87 auto s = spirv.data();
88
89 // Endian-swap if we need to.
90 if (s[0] == swap_endian(MagicNumber))
91 transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
92
93 if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
94 SPIRV_CROSS_THROW("Invalid SPIRV format.");
95
96 uint32_t bound = s[3];
97
98 const uint32_t MaximumNumberOfIDs = 0x3fffff;
99 if (bound > MaximumNumberOfIDs)
100 SPIRV_CROSS_THROW("ID bound exceeds limit of 0x3fffff.\n");
101
102 ir.set_id_bounds(bound);
103
104 uint32_t offset = 5;
105
106 SmallVector<Instruction> instructions;
107 while (offset < len)
108 {
109 Instruction instr = {};
110 instr.op = spirv[offset] & 0xffff;
111 instr.count = (spirv[offset] >> 16) & 0xffff;
112
113 if (instr.count == 0)
114 SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
115
116 instr.offset = offset + 1;
117 instr.length = instr.count - 1;
118
119 offset += instr.count;
120
121 if (offset > spirv.size())
122 SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
123
124 instructions.push_back(instr);
125 }
126
127 for (auto &i : instructions)
128 parse(i);
129
130 for (auto &fixup : forward_pointer_fixups)
131 {
132 auto &target = get<SPIRType>(fixup.first);
133 auto &source = get<SPIRType>(fixup.second);
134 target.member_types = source.member_types;
135 target.basetype = source.basetype;
136 target.self = source.self;
137 }
138 forward_pointer_fixups.clear();
139
140 if (current_function)
141 SPIRV_CROSS_THROW("Function was not terminated.");
142 if (current_block)
143 SPIRV_CROSS_THROW("Block was not terminated.");
144 if (ir.default_entry_point == 0)
145 SPIRV_CROSS_THROW("There is no entry point in the SPIR-V module.");
146 }
147
148 const uint32_t *Parser::stream(const Instruction &instr) const
149 {
150 // If we're not going to use any arguments, just return nullptr.
151 // We want to avoid case where we return an out of range pointer
152 // that trips debug assertions on some platforms.
153 if (!instr.length)
154 return nullptr;
155
156 if (instr.offset + instr.length > ir.spirv.size())
157 SPIRV_CROSS_THROW("Compiler::stream() out of range.");
158 return &ir.spirv[instr.offset];
159 }
160
161 static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
162 {
163 string ret;
164 for (uint32_t i = offset; i < spirv.size(); i++)
165 {
166 uint32_t w = spirv[i];
167
168 for (uint32_t j = 0; j < 4; j++, w >>= 8)
169 {
170 char c = w & 0xff;
171 if (c == '\0')
172 return ret;
173 ret += c;
174 }
175 }
176
177 SPIRV_CROSS_THROW("String was not terminated before EOF");
178 }
179
180 void Parser::parse(const Instruction &instruction)
181 {
182 auto *ops = stream(instruction);
183 auto op = static_cast<Op>(instruction.op);
184 uint32_t length = instruction.length;
185
186 // HACK for glslang that might emit OpEmitMeshTasksEXT followed by return / branch.
187 // Instead of failing hard, just ignore it.
188 if (ignore_trailing_block_opcodes)
189 {
190 ignore_trailing_block_opcodes = false;
191 if (op == OpReturn || op == OpBranch || op == OpUnreachable)
192 return;
193 }
194
195 switch (op)
196 {
197 case OpSourceContinued:
198 case OpSourceExtension:
199 case OpNop:
200 case OpModuleProcessed:
201 break;
202
203 case OpString:
204 {
205 set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
206 break;
207 }
208
209 case OpMemoryModel:
210 ir.addressing_model = static_cast<AddressingModel>(ops[0]);
211 ir.memory_model = static_cast<MemoryModel>(ops[1]);
212 break;
213
214 case OpSource:
215 {
216 auto lang = static_cast<SourceLanguage>(ops[0]);
217 switch (lang)
218 {
219 case SourceLanguageESSL:
220 ir.source.es = true;
221 ir.source.version = ops[1];
222 ir.source.known = true;
223 ir.source.hlsl = false;
224 break;
225
226 case SourceLanguageGLSL:
227 ir.source.es = false;
228 ir.source.version = ops[1];
229 ir.source.known = true;
230 ir.source.hlsl = false;
231 break;
232
233 case SourceLanguageHLSL:
234 // For purposes of cross-compiling, this is GLSL 450.
235 ir.source.es = false;
236 ir.source.version = 450;
237 ir.source.known = true;
238 ir.source.hlsl = true;
239 break;
240
241 default:
242 ir.source.known = false;
243 break;
244 }
245 break;
246 }
247
248 case OpUndef:
249 {
250 uint32_t result_type = ops[0];
251 uint32_t id = ops[1];
252 set<SPIRUndef>(id, result_type);
253 if (current_block)
254 current_block->ops.push_back(instruction);
255 break;
256 }
257
258 case OpCapability:
259 {
260 uint32_t cap = ops[0];
261 if (cap == CapabilityKernel)
262 SPIRV_CROSS_THROW("Kernel capability not supported.");
263
264 ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
265 break;
266 }
267
268 case OpExtension:
269 {
270 auto ext = extract_string(ir.spirv, instruction.offset);
271 ir.declared_extensions.push_back(std::move(ext));
272 break;
273 }
274
275 case OpExtInstImport:
276 {
277 uint32_t id = ops[0];
278
279 SPIRExtension::Extension spirv_ext = SPIRExtension::Unsupported;
280
281 auto ext = extract_string(ir.spirv, instruction.offset + 1);
282 if (ext == "GLSL.std.450")
283 spirv_ext = SPIRExtension::GLSL;
284 else if (ext == "DebugInfo")
285 spirv_ext = SPIRExtension::SPV_debug_info;
286 else if (ext == "SPV_AMD_shader_ballot")
287 spirv_ext = SPIRExtension::SPV_AMD_shader_ballot;
288 else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
289 spirv_ext = SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter;
290 else if (ext == "SPV_AMD_shader_trinary_minmax")
291 spirv_ext = SPIRExtension::SPV_AMD_shader_trinary_minmax;
292 else if (ext == "SPV_AMD_gcn_shader")
293 spirv_ext = SPIRExtension::SPV_AMD_gcn_shader;
294 else if (ext == "NonSemantic.DebugPrintf")
295 spirv_ext = SPIRExtension::NonSemanticDebugPrintf;
296 else if (ext == "NonSemantic.Shader.DebugInfo.100")
297 spirv_ext = SPIRExtension::NonSemanticShaderDebugInfo;
298 else if (ext.find("NonSemantic.") == 0)
299 spirv_ext = SPIRExtension::NonSemanticGeneric;
300
301 set<SPIRExtension>(id, spirv_ext);
302 // Other SPIR-V extensions which have ExtInstrs are currently not supported.
303
304 break;
305 }
306
307 case OpExtInst:
308 case OpExtInstWithForwardRefsKHR:
309 {
310 // The SPIR-V debug information extended instructions might come at global scope.
311 if (current_block)
312 {
313 current_block->ops.push_back(instruction);
314 if (length >= 2)
315 {
316 const auto *type = maybe_get<SPIRType>(ops[0]);
317 if (type)
318 ir.load_type_width.insert({ ops[1], type->width });
319 }
320 }
321 break;
322 }
323
324 case OpEntryPoint:
325 {
326 auto itr =
327 ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
328 extract_string(ir.spirv, instruction.offset + 2))));
329 auto &e = itr.first->second;
330
331 // Strings need nul-terminator and consume the whole word.
332 uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
333
334 for (uint32_t i = strlen_words + 2; i < instruction.length; i++)
335 e.interface_variables.push_back(ops[i]);
336
337 // Set the name of the entry point in case OpName is not provided later.
338 ir.set_name(ops[1], e.name);
339
340 // If we don't have an entry, make the first one our "default".
341 if (!ir.default_entry_point)
342 ir.default_entry_point = ops[1];
343 break;
344 }
345
346 case OpExecutionMode:
347 {
348 auto &execution = ir.entry_points[ops[0]];
349 auto mode = static_cast<ExecutionMode>(ops[1]);
350 execution.flags.set(mode);
351
352 switch (mode)
353 {
354 case ExecutionModeInvocations:
355 execution.invocations = ops[2];
356 break;
357
358 case ExecutionModeLocalSize:
359 execution.workgroup_size.x = ops[2];
360 execution.workgroup_size.y = ops[3];
361 execution.workgroup_size.z = ops[4];
362 break;
363
364 case ExecutionModeOutputVertices:
365 execution.output_vertices = ops[2];
366 break;
367
368 case ExecutionModeOutputPrimitivesEXT:
369 execution.output_primitives = ops[2];
370 break;
371
372 default:
373 break;
374 }
375 break;
376 }
377
378 case OpExecutionModeId:
379 {
380 auto &execution = ir.entry_points[ops[0]];
381 auto mode = static_cast<ExecutionMode>(ops[1]);
382 execution.flags.set(mode);
383
384 switch (mode)
385 {
386 case ExecutionModeLocalSizeId:
387 execution.workgroup_size.id_x = ops[2];
388 execution.workgroup_size.id_y = ops[3];
389 execution.workgroup_size.id_z = ops[4];
390 break;
391
392 case ExecutionModeFPFastMathDefault:
393 execution.fp_fast_math_defaults[ops[2]] = ops[3];
394 break;
395
396 default:
397 break;
398 }
399 break;
400 }
401
402 case OpName:
403 {
404 uint32_t id = ops[0];
405 ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
406 break;
407 }
408
409 case OpMemberName:
410 {
411 uint32_t id = ops[0];
412 uint32_t member = ops[1];
413 ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
414 break;
415 }
416
417 case OpDecorationGroup:
418 {
419 // Noop, this simply means an ID should be a collector of decorations.
420 // The meta array is already a flat array of decorations which will contain the relevant decorations.
421 break;
422 }
423
424 case OpGroupDecorate:
425 {
426 uint32_t group_id = ops[0];
427 auto &decorations = ir.meta[group_id].decoration;
428 auto &flags = decorations.decoration_flags;
429
430 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
431 // i.e., we cannot just copy the meta structure directly.
432 for (uint32_t i = 1; i < length; i++)
433 {
434 uint32_t target = ops[i];
435 flags.for_each_bit([&](uint32_t bit) {
436 auto decoration = static_cast<Decoration>(bit);
437
438 if (decoration_is_string(decoration))
439 {
440 ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
441 }
442 else
443 {
444 ir.meta[target].decoration_word_offset[decoration] =
445 ir.meta[group_id].decoration_word_offset[decoration];
446 ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
447 }
448 });
449 }
450 break;
451 }
452
453 case OpGroupMemberDecorate:
454 {
455 uint32_t group_id = ops[0];
456 auto &flags = ir.meta[group_id].decoration.decoration_flags;
457
458 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
459 // i.e., we cannot just copy the meta structure directly.
460 for (uint32_t i = 1; i + 1 < length; i += 2)
461 {
462 uint32_t target = ops[i + 0];
463 uint32_t index = ops[i + 1];
464 flags.for_each_bit([&](uint32_t bit) {
465 auto decoration = static_cast<Decoration>(bit);
466
467 if (decoration_is_string(decoration))
468 ir.set_member_decoration_string(target, index, decoration,
469 ir.get_decoration_string(group_id, decoration));
470 else
471 ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
472 });
473 }
474 break;
475 }
476
477 case OpDecorate:
478 case OpDecorateId:
479 {
480 // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
481 // so merge decorate and decorate-id here.
482 uint32_t id = ops[0];
483
484 auto decoration = static_cast<Decoration>(ops[1]);
485 if (length >= 3)
486 {
487 ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
488 ir.set_decoration(id, decoration, ops[2]);
489 }
490 else
491 ir.set_decoration(id, decoration);
492
493 break;
494 }
495
496 case OpDecorateStringGOOGLE:
497 {
498 uint32_t id = ops[0];
499 auto decoration = static_cast<Decoration>(ops[1]);
500 ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
501 break;
502 }
503
504 case OpMemberDecorate:
505 {
506 uint32_t id = ops[0];
507 uint32_t member = ops[1];
508 auto decoration = static_cast<Decoration>(ops[2]);
509 if (length >= 4)
510 ir.set_member_decoration(id, member, decoration, ops[3]);
511 else
512 ir.set_member_decoration(id, member, decoration);
513 break;
514 }
515
516 case OpMemberDecorateStringGOOGLE:
517 {
518 uint32_t id = ops[0];
519 uint32_t member = ops[1];
520 auto decoration = static_cast<Decoration>(ops[2]);
521 ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
522 break;
523 }
524
525 // Build up basic types.
526 case OpTypeVoid:
527 {
528 uint32_t id = ops[0];
529 auto &type = set<SPIRType>(id, op);
530 type.basetype = SPIRType::Void;
531 break;
532 }
533
534 case OpTypeBool:
535 {
536 uint32_t id = ops[0];
537 auto &type = set<SPIRType>(id, op);
538 type.basetype = SPIRType::Boolean;
539 type.width = 1;
540 break;
541 }
542
543 case OpTypeFloat:
544 {
545 uint32_t id = ops[0];
546 uint32_t width = ops[1];
547 auto &type = set<SPIRType>(id, op);
548
549 if (width != 16 && width != 8 && length > 2)
550 SPIRV_CROSS_THROW("Unrecognized FP encoding mode for OpTypeFloat.");
551
552 if (width == 64)
553 type.basetype = SPIRType::Double;
554 else if (width == 32)
555 type.basetype = SPIRType::Float;
556 else if (width == 16)
557 {
558 if (length > 2)
559 {
560 if (ops[2] == spv::FPEncodingBFloat16KHR)
561 type.basetype = SPIRType::BFloat16;
562 else
563 SPIRV_CROSS_THROW("Unrecognized encoding for OpTypeFloat 16.");
564 }
565 else
566 type.basetype = SPIRType::Half;
567 }
568 else if (width == 8)
569 {
570 if (length < 2)
571 SPIRV_CROSS_THROW("Missing encoding for OpTypeFloat 8.");
572 else if (ops[2] == spv::FPEncodingFloat8E4M3EXT)
573 type.basetype = SPIRType::FloatE4M3;
574 else if (ops[2] == spv::FPEncodingFloat8E5M2EXT)
575 type.basetype = SPIRType::FloatE5M2;
576 else
577 SPIRV_CROSS_THROW("Invalid encoding for OpTypeFloat 8.");
578 }
579 else
580 SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
581 type.width = width;
582 break;
583 }
584
585 case OpTypeInt:
586 {
587 uint32_t id = ops[0];
588 uint32_t width = ops[1];
589 bool signedness = ops[2] != 0;
590 auto &type = set<SPIRType>(id, op);
591 type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
592 type.width = width;
593 break;
594 }
595
596 // Build composite types by "inheriting".
597 // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
598 // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
599 case OpTypeVector:
600 {
601 uint32_t id = ops[0];
602 uint32_t vecsize = ops[2];
603
604 auto &base = get<SPIRType>(ops[1]);
605 auto &vecbase = set<SPIRType>(id, base);
606
607 vecbase.op = op;
608 vecbase.vecsize = vecsize;
609 vecbase.self = id;
610 vecbase.parent_type = ops[1];
611 break;
612 }
613
614 case OpTypeMatrix:
615 {
616 uint32_t id = ops[0];
617 uint32_t colcount = ops[2];
618
619 auto &base = get<SPIRType>(ops[1]);
620 auto &matrixbase = set<SPIRType>(id, base);
621
622 matrixbase.op = op;
623 matrixbase.columns = colcount;
624 matrixbase.self = id;
625 matrixbase.parent_type = ops[1];
626 break;
627 }
628
629 case OpTypeCooperativeMatrixKHR:
630 {
631 uint32_t id = ops[0];
632 auto &base = get<SPIRType>(ops[1]);
633 auto &matrixbase = set<SPIRType>(id, base);
634
635 matrixbase.op = op;
636 matrixbase.cooperative.scope_id = ops[2];
637 matrixbase.cooperative.rows_id = ops[3];
638 matrixbase.cooperative.columns_id = ops[4];
639 matrixbase.cooperative.use_id = ops[5];
640 matrixbase.self = id;
641 matrixbase.parent_type = ops[1];
642 break;
643 }
644
645 case OpTypeArray:
646 {
647 uint32_t id = ops[0];
648 uint32_t tid = ops[1];
649 auto &base = get<SPIRType>(tid);
650 auto &arraybase = set<SPIRType>(id, base);
651
652 arraybase.op = op;
653 arraybase.parent_type = tid;
654
655 uint32_t cid = ops[2];
656 ir.mark_used_as_array_length(cid);
657 auto *c = maybe_get<SPIRConstant>(cid);
658 bool literal = c && !c->specialization;
659
660 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
661 // references.
662 if (base.forward_pointer)
663 forward_pointer_fixups.push_back({ id, tid });
664
665 arraybase.array_size_literal.push_back(literal);
666 arraybase.array.push_back(literal ? c->scalar() : cid);
667
668 // .self resolves down to non-array/non-pointer type.
669 arraybase.self = base.self;
670 break;
671 }
672
673 case OpTypeRuntimeArray:
674 {
675 uint32_t id = ops[0];
676
677 auto &base = get<SPIRType>(ops[1]);
678 auto &arraybase = set<SPIRType>(id, base);
679
680 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
681 // references.
682 if (base.forward_pointer)
683 forward_pointer_fixups.push_back({ id, ops[1] });
684
685 arraybase.op = op;
686 arraybase.array.push_back(0);
687 arraybase.array_size_literal.push_back(true);
688 arraybase.parent_type = ops[1];
689
690 // .self resolves down to non-array/non-pointer type.
691 arraybase.self = base.self;
692 break;
693 }
694
695 case OpTypeImage:
696 {
697 uint32_t id = ops[0];
698 auto &type = set<SPIRType>(id, op);
699 type.basetype = SPIRType::Image;
700 type.image.type = ops[1];
701 type.image.dim = static_cast<Dim>(ops[2]);
702 type.image.depth = ops[3] == 1;
703 type.image.arrayed = ops[4] != 0;
704 type.image.ms = ops[5] != 0;
705 type.image.sampled = ops[6];
706 type.image.format = static_cast<ImageFormat>(ops[7]);
707 type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
708 break;
709 }
710
711 case OpTypeSampledImage:
712 {
713 uint32_t id = ops[0];
714 uint32_t imagetype = ops[1];
715 auto &type = set<SPIRType>(id, op);
716 type = get<SPIRType>(imagetype);
717 type.basetype = SPIRType::SampledImage;
718 type.self = id;
719 break;
720 }
721
722 case OpTypeSampler:
723 {
724 uint32_t id = ops[0];
725 auto &type = set<SPIRType>(id, op);
726 type.basetype = SPIRType::Sampler;
727 break;
728 }
729
730 case OpTypePointer:
731 {
732 uint32_t id = ops[0];
733
734 // Very rarely, we might receive a FunctionPrototype here.
735 // We won't be able to compile it, but we shouldn't crash when parsing.
736 // We should be able to reflect.
737 auto *base = maybe_get<SPIRType>(ops[2]);
738 auto &ptrbase = set<SPIRType>(id, op);
739
740 if (base)
741 {
742 ptrbase = *base;
743 ptrbase.op = op;
744 }
745
746 ptrbase.pointer = true;
747 ptrbase.pointer_depth++;
748 ptrbase.storage = static_cast<StorageClass>(ops[1]);
749
750 if (ptrbase.storage == StorageClassAtomicCounter)
751 ptrbase.basetype = SPIRType::AtomicCounter;
752
753 if (base && base->forward_pointer)
754 forward_pointer_fixups.push_back({ id, ops[2] });
755
756 ptrbase.parent_type = ops[2];
757
758 // Do NOT set ptrbase.self!
759 break;
760 }
761
762 case OpTypeForwardPointer:
763 {
764 uint32_t id = ops[0];
765 auto &ptrbase = set<SPIRType>(id, op);
766 ptrbase.pointer = true;
767 ptrbase.pointer_depth++;
768 ptrbase.storage = static_cast<StorageClass>(ops[1]);
769 ptrbase.forward_pointer = true;
770
771 if (ptrbase.storage == StorageClassAtomicCounter)
772 ptrbase.basetype = SPIRType::AtomicCounter;
773
774 break;
775 }
776
777 case OpTypeStruct:
778 {
779 uint32_t id = ops[0];
780 auto &type = set<SPIRType>(id, op);
781 type.basetype = SPIRType::Struct;
782 for (uint32_t i = 1; i < length; i++)
783 type.member_types.push_back(ops[i]);
784
785 // Check if we have seen this struct type before, with just different
786 // decorations.
787 //
788 // Add workaround for issue #17 as well by looking at OpName for the struct
789 // types, which we shouldn't normally do.
790 // We should not normally have to consider type aliases like this to begin with
791 // however ... glslang issues #304, #307 cover this.
792
793 // For stripped names, never consider struct type aliasing.
794 // We risk declaring the same struct multiple times, but type-punning is not allowed
795 // so this is safe.
796 bool consider_aliasing = !ir.get_name(type.self).empty();
797 if (consider_aliasing)
798 {
799 for (auto &other : global_struct_cache)
800 {
801 if (ir.get_name(type.self) == ir.get_name(other) &&
802 types_are_logically_equivalent(type, get<SPIRType>(other)))
803 {
804 type.type_alias = other;
805 break;
806 }
807 }
808
809 if (type.type_alias == TypeID(0))
810 global_struct_cache.push_back(id);
811 }
812 break;
813 }
814
815 case OpTypeFunction:
816 {
817 uint32_t id = ops[0];
818 uint32_t ret = ops[1];
819
820 auto &func = set<SPIRFunctionPrototype>(id, ret);
821 for (uint32_t i = 2; i < length; i++)
822 func.parameter_types.push_back(ops[i]);
823 break;
824 }
825
826 case OpTypeAccelerationStructureKHR:
827 {
828 uint32_t id = ops[0];
829 auto &type = set<SPIRType>(id, op);
830 type.basetype = SPIRType::AccelerationStructure;
831 break;
832 }
833
834 case OpTypeRayQueryKHR:
835 {
836 uint32_t id = ops[0];
837 auto &type = set<SPIRType>(id, op);
838 type.basetype = SPIRType::RayQuery;
839 break;
840 }
841
842 // Variable declaration
843 // All variables are essentially pointers with a storage qualifier.
844 case OpVariable:
845 {
846 uint32_t type = ops[0];
847 uint32_t id = ops[1];
848 auto storage = static_cast<StorageClass>(ops[2]);
849 uint32_t initializer = length == 4 ? ops[3] : 0;
850
851 if (storage == StorageClassFunction)
852 {
853 if (!current_function)
854 SPIRV_CROSS_THROW("No function currently in scope");
855 current_function->add_local_variable(id);
856 }
857
858 set<SPIRVariable>(id, type, storage, initializer);
859 break;
860 }
861
862 // OpPhi
863 // OpPhi is a fairly magical opcode.
864 // It selects temporary variables based on which parent block we *came from*.
865 // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
866 // variable to emulate SSA Phi.
867 case OpPhi:
868 {
869 if (!current_function)
870 SPIRV_CROSS_THROW("No function currently in scope");
871 if (!current_block)
872 SPIRV_CROSS_THROW("No block currently in scope");
873
874 uint32_t result_type = ops[0];
875 uint32_t id = ops[1];
876
877 // Instead of a temporary, create a new function-wide temporary with this ID instead.
878 auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
879 var.phi_variable = true;
880
881 current_function->add_local_variable(id);
882
883 for (uint32_t i = 2; i + 2 <= length; i += 2)
884 current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
885 break;
886 }
887
888 // Constants
889 case OpSpecConstant:
890 case OpConstant:
891 case OpConstantCompositeReplicateEXT:
892 case OpSpecConstantCompositeReplicateEXT:
893 {
894 uint32_t id = ops[1];
895 auto &type = get<SPIRType>(ops[0]);
896 if (op == OpConstantCompositeReplicateEXT || op == OpSpecConstantCompositeReplicateEXT)
897 {
898 auto subconstant = uint32_t(ops[2]);
899 set<SPIRConstant>(id, ops[0], &subconstant, 1, op == OpSpecConstantCompositeReplicateEXT, true);
900 }
901 else
902 {
903
904 if (type.width > 32)
905 set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
906 else
907 set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
908 }
909 break;
910 }
911
912 case OpSpecConstantFalse:
913 case OpConstantFalse:
914 {
915 uint32_t id = ops[1];
916 set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
917 break;
918 }
919
920 case OpSpecConstantTrue:
921 case OpConstantTrue:
922 {
923 uint32_t id = ops[1];
924 set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
925 break;
926 }
927
928 case OpConstantNull:
929 {
930 uint32_t id = ops[1];
931 uint32_t type = ops[0];
932 ir.make_constant_null(id, type, true);
933 break;
934 }
935
936 case OpSpecConstantComposite:
937 case OpConstantComposite:
938 {
939 uint32_t id = ops[1];
940 uint32_t type = ops[0];
941
942 auto &ctype = get<SPIRType>(type);
943
944 // We can have constants which are structs and arrays.
945 // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
946 // can refer to.
947 if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
948 {
949 set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
950 }
951 else
952 {
953 uint32_t elements = length - 2;
954 if (elements > 4)
955 SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
956
957 SPIRConstant remapped_constant_ops[4];
958 const SPIRConstant *c[4];
959 for (uint32_t i = 0; i < elements; i++)
960 {
961 // Specialization constants operations can also be part of this.
962 // We do not know their value, so any attempt to query SPIRConstant later
963 // will fail. We can only propagate the ID of the expression and use to_expression on it.
964 auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
965 auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
966 if (constant_op)
967 {
968 if (op == OpConstantComposite)
969 SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
970
971 remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
972 remapped_constant_ops[i].self = constant_op->self;
973 remapped_constant_ops[i].constant_type = constant_op->basetype;
974 remapped_constant_ops[i].specialization = true;
975 c[i] = &remapped_constant_ops[i];
976 }
977 else if (undef_op)
978 {
979 // Undefined, just pick 0.
980 remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
981 remapped_constant_ops[i].constant_type = undef_op->basetype;
982 c[i] = &remapped_constant_ops[i];
983 }
984 else
985 c[i] = &get<SPIRConstant>(ops[2 + i]);
986 }
987 set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
988 }
989 break;
990 }
991
992 // Functions
993 case OpFunction:
994 {
995 uint32_t res = ops[0];
996 uint32_t id = ops[1];
997 // Control
998 uint32_t type = ops[3];
999
1000 if (current_function)
1001 SPIRV_CROSS_THROW("Must end a function before starting a new one!");
1002
1003 current_function = &set<SPIRFunction>(id, res, type);
1004 break;
1005 }
1006
1007 case OpFunctionParameter:
1008 {
1009 uint32_t type = ops[0];
1010 uint32_t id = ops[1];
1011
1012 if (!current_function)
1013 SPIRV_CROSS_THROW("Must be in a function!");
1014
1015 current_function->add_parameter(type, id);
1016 set<SPIRVariable>(id, type, StorageClassFunction);
1017 break;
1018 }
1019
1020 case OpFunctionEnd:
1021 {
1022 if (current_block)
1023 {
1024 // Very specific error message, but seems to come up quite often.
1025 SPIRV_CROSS_THROW(
1026 "Cannot end a function before ending the current block.\n"
1027 "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
1028 }
1029 current_function = nullptr;
1030 break;
1031 }
1032
1033 // Blocks
1034 case OpLabel:
1035 {
1036 // OpLabel always starts a block.
1037 if (!current_function)
1038 SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
1039
1040 uint32_t id = ops[0];
1041
1042 current_function->blocks.push_back(id);
1043 if (!current_function->entry_block)
1044 current_function->entry_block = id;
1045
1046 if (current_block)
1047 SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
1048
1049 current_block = &set<SPIRBlock>(id);
1050 break;
1051 }
1052
1053 // Branch instructions end blocks.
1054 case OpBranch:
1055 {
1056 if (!current_block)
1057 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1058
1059 uint32_t target = ops[0];
1060 current_block->terminator = SPIRBlock::Direct;
1061 current_block->next_block = target;
1062 current_block = nullptr;
1063 break;
1064 }
1065
1066 case OpBranchConditional:
1067 {
1068 if (!current_block)
1069 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1070
1071 current_block->condition = ops[0];
1072 current_block->true_block = ops[1];
1073 current_block->false_block = ops[2];
1074
1075 current_block->terminator = SPIRBlock::Select;
1076
1077 if (current_block->true_block == current_block->false_block)
1078 {
1079 // Bogus conditional, translate to a direct branch.
1080 // Avoids some ugly edge cases later when analyzing CFGs.
1081
1082 // There are some super jank cases where the merge block is different from the true/false,
1083 // and later branches can "break" out of the selection construct this way.
1084 // This is complete nonsense, but CTS hits this case.
1085 // In this scenario, we should see the selection construct as more of a Switch with one default case.
1086 // The problem here is that this breaks any attempt to break out of outer switch statements,
1087 // but it's theoretically solvable if this ever comes up using the ladder breaking system ...
1088
1089 if (current_block->true_block != current_block->next_block &&
1090 current_block->merge == SPIRBlock::MergeSelection)
1091 {
1092 uint32_t ids = ir.increase_bound_by(2);
1093
1094 auto &type = set<SPIRType>(ids, OpTypeInt);
1095 type.basetype = SPIRType::Int;
1096 type.width = 32;
1097 auto &c = set<SPIRConstant>(ids + 1, ids);
1098
1099 current_block->condition = c.self;
1100 current_block->default_block = current_block->true_block;
1101 current_block->terminator = SPIRBlock::MultiSelect;
1102 ir.block_meta[current_block->next_block] &= ~ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
1103 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
1104 }
1105 else
1106 {
1107 // Collapse loops if we have to.
1108 bool collapsed_loop = current_block->true_block == current_block->merge_block &&
1109 current_block->merge == SPIRBlock::MergeLoop;
1110
1111 if (collapsed_loop)
1112 {
1113 ir.block_meta[current_block->merge_block] &= ~ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1114 ir.block_meta[current_block->continue_block] &= ~ParsedIR::BLOCK_META_CONTINUE_BIT;
1115 }
1116
1117 current_block->next_block = current_block->true_block;
1118 current_block->condition = 0;
1119 current_block->true_block = 0;
1120 current_block->false_block = 0;
1121 current_block->merge_block = 0;
1122 current_block->merge = SPIRBlock::MergeNone;
1123 current_block->terminator = SPIRBlock::Direct;
1124 }
1125 }
1126
1127 current_block = nullptr;
1128 break;
1129 }
1130
1131 case OpSwitch:
1132 {
1133 if (!current_block)
1134 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1135
1136 current_block->terminator = SPIRBlock::MultiSelect;
1137
1138 current_block->condition = ops[0];
1139 current_block->default_block = ops[1];
1140
1141 uint32_t remaining_ops = length - 2;
1142 if ((remaining_ops % 2) == 0)
1143 {
1144 for (uint32_t i = 2; i + 2 <= length; i += 2)
1145 current_block->cases_32bit.push_back({ ops[i], ops[i + 1] });
1146 }
1147
1148 if ((remaining_ops % 3) == 0)
1149 {
1150 for (uint32_t i = 2; i + 3 <= length; i += 3)
1151 {
1152 uint64_t value = (static_cast<uint64_t>(ops[i + 1]) << 32) | ops[i];
1153 current_block->cases_64bit.push_back({ value, ops[i + 2] });
1154 }
1155 }
1156
1157 // If we jump to next block, make it break instead since we're inside a switch case block at that point.
1158 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
1159
1160 current_block = nullptr;
1161 break;
1162 }
1163
1164 case OpKill:
1165 case OpTerminateInvocation:
1166 {
1167 if (!current_block)
1168 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1169 current_block->terminator = SPIRBlock::Kill;
1170 current_block = nullptr;
1171 break;
1172 }
1173
1174 case OpTerminateRayKHR:
1175 // NV variant is not a terminator.
1176 if (!current_block)
1177 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1178 current_block->terminator = SPIRBlock::TerminateRay;
1179 current_block = nullptr;
1180 break;
1181
1182 case OpIgnoreIntersectionKHR:
1183 // NV variant is not a terminator.
1184 if (!current_block)
1185 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1186 current_block->terminator = SPIRBlock::IgnoreIntersection;
1187 current_block = nullptr;
1188 break;
1189
1190 case OpEmitMeshTasksEXT:
1191 if (!current_block)
1192 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1193 current_block->terminator = SPIRBlock::EmitMeshTasks;
1194 for (uint32_t i = 0; i < 3; i++)
1195 current_block->mesh.groups[i] = ops[i];
1196 current_block->mesh.payload = length >= 4 ? ops[3] : 0;
1197 current_block = nullptr;
1198 // Currently glslang is bugged and does not treat EmitMeshTasksEXT as a terminator.
1199 ignore_trailing_block_opcodes = true;
1200 break;
1201
1202 case OpReturn:
1203 {
1204 if (!current_block)
1205 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1206 current_block->terminator = SPIRBlock::Return;
1207 current_block = nullptr;
1208 break;
1209 }
1210
1211 case OpReturnValue:
1212 {
1213 if (!current_block)
1214 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1215 current_block->terminator = SPIRBlock::Return;
1216 current_block->return_value = ops[0];
1217 current_block = nullptr;
1218 break;
1219 }
1220
1221 case OpUnreachable:
1222 {
1223 if (!current_block)
1224 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1225 current_block->terminator = SPIRBlock::Unreachable;
1226 current_block = nullptr;
1227 break;
1228 }
1229
1230 case OpSelectionMerge:
1231 {
1232 if (!current_block)
1233 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1234
1235 current_block->next_block = ops[0];
1236 current_block->merge = SPIRBlock::MergeSelection;
1237 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
1238
1239 if (length >= 2)
1240 {
1241 if (ops[1] & SelectionControlFlattenMask)
1242 current_block->hint = SPIRBlock::HintFlatten;
1243 else if (ops[1] & SelectionControlDontFlattenMask)
1244 current_block->hint = SPIRBlock::HintDontFlatten;
1245 }
1246 break;
1247 }
1248
1249 case OpLoopMerge:
1250 {
1251 if (!current_block)
1252 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1253
1254 current_block->merge_block = ops[0];
1255 current_block->continue_block = ops[1];
1256 current_block->merge = SPIRBlock::MergeLoop;
1257
1258 ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
1259 ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1260
1261 ir.continue_block_to_loop_header[current_block->continue_block] = BlockID(current_block->self);
1262
1263 // Don't add loop headers to continue blocks,
1264 // which would make it impossible branch into the loop header since
1265 // they are treated as continues.
1266 if (current_block->continue_block != BlockID(current_block->self))
1267 ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
1268
1269 if (length >= 3)
1270 {
1271 if (ops[2] & LoopControlUnrollMask)
1272 current_block->hint = SPIRBlock::HintUnroll;
1273 else if (ops[2] & LoopControlDontUnrollMask)
1274 current_block->hint = SPIRBlock::HintDontUnroll;
1275 }
1276 break;
1277 }
1278
1279 case OpSpecConstantOp:
1280 {
1281 if (length < 3)
1282 SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
1283
1284 uint32_t result_type = ops[0];
1285 uint32_t id = ops[1];
1286 auto spec_op = static_cast<Op>(ops[2]);
1287
1288 set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
1289 break;
1290 }
1291
1292 case OpLine:
1293 {
1294 // OpLine might come at global scope, but we don't care about those since they will not be declared in any
1295 // meaningful correct order.
1296 // Ignore all OpLine directives which live outside a function.
1297 if (current_block)
1298 current_block->ops.push_back(instruction);
1299
1300 // Line directives may arrive before first OpLabel.
1301 // Treat this as the line of the function declaration,
1302 // so warnings for arguments can propagate properly.
1303 if (current_function)
1304 {
1305 // Store the first one we find and emit it before creating the function prototype.
1306 if (current_function->entry_line.file_id == 0)
1307 {
1308 current_function->entry_line.file_id = ops[0];
1309 current_function->entry_line.line_literal = ops[1];
1310 }
1311 }
1312 break;
1313 }
1314
1315 case OpNoLine:
1316 {
1317 // OpNoLine might come at global scope.
1318 if (current_block)
1319 current_block->ops.push_back(instruction);
1320 break;
1321 }
1322
1323 // Actual opcodes.
1324 default:
1325 {
1326 if (length >= 2)
1327 {
1328 const auto *type = maybe_get<SPIRType>(ops[0]);
1329 if (type)
1330 ir.load_type_width.insert({ ops[1], type->width });
1331 }
1332
1333 if (!current_block)
1334 SPIRV_CROSS_THROW("Currently no block to insert opcode.");
1335
1336 current_block->ops.push_back(instruction);
1337 break;
1338 }
1339 }
1340 }
1341
1342 bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
1343 {
1344 if (a.basetype != b.basetype)
1345 return false;
1346 if (a.width != b.width)
1347 return false;
1348 if (a.vecsize != b.vecsize)
1349 return false;
1350 if (a.columns != b.columns)
1351 return false;
1352 if (a.array.size() != b.array.size())
1353 return false;
1354
1355 size_t array_count = a.array.size();
1356 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
1357 return false;
1358
1359 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
1360 {
1361 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
1362 return false;
1363 }
1364
1365 if (a.member_types.size() != b.member_types.size())
1366 return false;
1367
1368 size_t member_types = a.member_types.size();
1369 for (size_t i = 0; i < member_types; i++)
1370 {
1371 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
1372 return false;
1373 }
1374
1375 return true;
1376 }
1377
1378 bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
1379 {
1380 auto &type = get<SPIRType>(v.basetype);
1381
1382 auto *type_meta = ir.find_meta(type.self);
1383
1384 bool ssbo = v.storage == StorageClassStorageBuffer ||
1385 (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
1386 bool image = type.basetype == SPIRType::Image;
1387 bool counter = type.basetype == SPIRType::AtomicCounter;
1388
1389 bool is_restrict;
1390 if (ssbo)
1391 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
1392 else
1393 is_restrict = ir.has_decoration(v.self, DecorationRestrict);
1394
1395 return !is_restrict && (ssbo || image || counter);
1396 }
1397 } // namespace SPIRV_CROSS_NAMESPACE