blob: af0b2b35d750ea164b7954f81d952a46b7360b08 [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:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200165 case OpNoLine:
lifpan91610962018-11-13 14:28:38 +0800166 case OpModuleProcessed:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200167 break;
168
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +0200169 case OpString:
170 {
171 set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
172 break;
173 }
174
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200175 case OpMemoryModel:
176 ir.addressing_model = static_cast<AddressingModel>(ops[0]);
177 ir.memory_model = static_cast<MemoryModel>(ops[1]);
178 break;
179
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200180 case OpSource:
181 {
182 auto lang = static_cast<SourceLanguage>(ops[0]);
183 switch (lang)
184 {
185 case SourceLanguageESSL:
186 ir.source.es = true;
187 ir.source.version = ops[1];
188 ir.source.known = true;
189 ir.source.hlsl = false;
190 break;
191
192 case SourceLanguageGLSL:
193 ir.source.es = false;
194 ir.source.version = ops[1];
195 ir.source.known = true;
196 ir.source.hlsl = false;
197 break;
198
199 case SourceLanguageHLSL:
200 // For purposes of cross-compiling, this is GLSL 450.
201 ir.source.es = false;
202 ir.source.version = 450;
203 ir.source.known = true;
204 ir.source.hlsl = true;
205 break;
206
207 default:
208 ir.source.known = false;
209 break;
210 }
211 break;
212 }
213
214 case OpUndef:
215 {
216 uint32_t result_type = ops[0];
217 uint32_t id = ops[1];
218 set<SPIRUndef>(id, result_type);
lifpan876627d2019-04-08 19:45:31 +0800219 if (current_block)
220 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200221 break;
222 }
223
224 case OpCapability:
225 {
226 uint32_t cap = ops[0];
227 if (cap == CapabilityKernel)
228 SPIRV_CROSS_THROW("Kernel capability not supported.");
229
230 ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
231 break;
232 }
233
234 case OpExtension:
235 {
236 auto ext = extract_string(ir.spirv, instruction.offset);
237 ir.declared_extensions.push_back(move(ext));
238 break;
239 }
240
241 case OpExtInstImport:
242 {
243 uint32_t id = ops[0];
244 auto ext = extract_string(ir.spirv, instruction.offset + 1);
245 if (ext == "GLSL.std.450")
246 set<SPIRExtension>(id, SPIRExtension::GLSL);
247 else if (ext == "SPV_AMD_shader_ballot")
248 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
249 else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
250 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
251 else if (ext == "SPV_AMD_shader_trinary_minmax")
252 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
253 else if (ext == "SPV_AMD_gcn_shader")
254 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
255 else
256 set<SPIRExtension>(id, SPIRExtension::Unsupported);
257
258 // Other SPIR-V extensions which have ExtInstrs are currently not supported.
259
260 break;
261 }
262
263 case OpEntryPoint:
264 {
265 auto itr =
266 ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
267 extract_string(ir.spirv, instruction.offset + 2))));
268 auto &e = itr.first->second;
269
270 // Strings need nul-terminator and consume the whole word.
271 uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
272 e.interface_variables.insert(end(e.interface_variables), ops + strlen_words + 2, ops + instruction.length);
273
274 // Set the name of the entry point in case OpName is not provided later.
275 ir.set_name(ops[1], e.name);
276
277 // If we don't have an entry, make the first one our "default".
278 if (!ir.default_entry_point)
279 ir.default_entry_point = ops[1];
280 break;
281 }
282
283 case OpExecutionMode:
284 {
285 auto &execution = ir.entry_points[ops[0]];
286 auto mode = static_cast<ExecutionMode>(ops[1]);
287 execution.flags.set(mode);
288
289 switch (mode)
290 {
291 case ExecutionModeInvocations:
292 execution.invocations = ops[2];
293 break;
294
295 case ExecutionModeLocalSize:
296 execution.workgroup_size.x = ops[2];
297 execution.workgroup_size.y = ops[3];
298 execution.workgroup_size.z = ops[4];
299 break;
300
301 case ExecutionModeOutputVertices:
302 execution.output_vertices = ops[2];
303 break;
304
305 default:
306 break;
307 }
308 break;
309 }
310
311 case OpName:
312 {
313 uint32_t id = ops[0];
314 ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
315 break;
316 }
317
318 case OpMemberName:
319 {
320 uint32_t id = ops[0];
321 uint32_t member = ops[1];
322 ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
323 break;
324 }
325
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100326 case OpDecorationGroup:
327 {
328 // Noop, this simply means an ID should be a collector of decorations.
329 // The meta array is already a flat array of decorations which will contain the relevant decorations.
330 break;
331 }
332
333 case OpGroupDecorate:
334 {
335 uint32_t group_id = ops[0];
336 auto &decorations = ir.meta[group_id].decoration;
337 auto &flags = decorations.decoration_flags;
338
339 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
340 // i.e., we cannot just copy the meta structure directly.
341 for (uint32_t i = 1; i < length; i++)
342 {
343 uint32_t target = ops[i];
344 flags.for_each_bit([&](uint32_t bit) {
345 auto decoration = static_cast<Decoration>(bit);
346
347 if (decoration_is_string(decoration))
348 {
349 ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
350 }
351 else
352 {
353 ir.meta[target].decoration_word_offset[decoration] =
354 ir.meta[group_id].decoration_word_offset[decoration];
355 ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
356 }
357 });
358 }
359 break;
360 }
361
362 case OpGroupMemberDecorate:
363 {
364 uint32_t group_id = ops[0];
365 auto &flags = ir.meta[group_id].decoration.decoration_flags;
366
367 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
368 // i.e., we cannot just copy the meta structure directly.
369 for (uint32_t i = 1; i + 1 < length; i += 2)
370 {
371 uint32_t target = ops[i + 0];
372 uint32_t index = ops[i + 1];
373 flags.for_each_bit([&](uint32_t bit) {
374 auto decoration = static_cast<Decoration>(bit);
375
376 if (decoration_is_string(decoration))
377 ir.set_member_decoration_string(target, index, decoration,
378 ir.get_decoration_string(group_id, decoration));
379 else
380 ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
381 });
382 }
383 break;
384 }
385
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200386 case OpDecorate:
387 case OpDecorateId:
388 {
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100389 // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
390 // so merge decorate and decorate-id here.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200391 uint32_t id = ops[0];
392
393 auto decoration = static_cast<Decoration>(ops[1]);
394 if (length >= 3)
395 {
396 ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
397 ir.set_decoration(id, decoration, ops[2]);
398 }
399 else
400 ir.set_decoration(id, decoration);
401
402 break;
403 }
404
405 case OpDecorateStringGOOGLE:
406 {
407 uint32_t id = ops[0];
408 auto decoration = static_cast<Decoration>(ops[1]);
409 ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
410 break;
411 }
412
413 case OpMemberDecorate:
414 {
415 uint32_t id = ops[0];
416 uint32_t member = ops[1];
417 auto decoration = static_cast<Decoration>(ops[2]);
418 if (length >= 4)
419 ir.set_member_decoration(id, member, decoration, ops[3]);
420 else
421 ir.set_member_decoration(id, member, decoration);
422 break;
423 }
424
425 case OpMemberDecorateStringGOOGLE:
426 {
427 uint32_t id = ops[0];
428 uint32_t member = ops[1];
429 auto decoration = static_cast<Decoration>(ops[2]);
430 ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
431 break;
432 }
433
434 // Build up basic types.
435 case OpTypeVoid:
436 {
437 uint32_t id = ops[0];
438 auto &type = set<SPIRType>(id);
439 type.basetype = SPIRType::Void;
440 break;
441 }
442
443 case OpTypeBool:
444 {
445 uint32_t id = ops[0];
446 auto &type = set<SPIRType>(id);
447 type.basetype = SPIRType::Boolean;
448 type.width = 1;
449 break;
450 }
451
452 case OpTypeFloat:
453 {
454 uint32_t id = ops[0];
455 uint32_t width = ops[1];
456 auto &type = set<SPIRType>(id);
457 if (width == 64)
458 type.basetype = SPIRType::Double;
459 else if (width == 32)
460 type.basetype = SPIRType::Float;
461 else if (width == 16)
462 type.basetype = SPIRType::Half;
463 else
464 SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
465 type.width = width;
466 break;
467 }
468
469 case OpTypeInt:
470 {
471 uint32_t id = ops[0];
472 uint32_t width = ops[1];
lifpanb21525b2018-11-28 14:20:24 +0800473 bool signedness = ops[2] != 0;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200474 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +0100475 type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200476 type.width = width;
477 break;
478 }
479
480 // Build composite types by "inheriting".
481 // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
482 // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
483 case OpTypeVector:
484 {
485 uint32_t id = ops[0];
486 uint32_t vecsize = ops[2];
487
488 auto &base = get<SPIRType>(ops[1]);
489 auto &vecbase = set<SPIRType>(id);
490
491 vecbase = base;
492 vecbase.vecsize = vecsize;
493 vecbase.self = id;
494 vecbase.parent_type = ops[1];
495 break;
496 }
497
498 case OpTypeMatrix:
499 {
500 uint32_t id = ops[0];
501 uint32_t colcount = ops[2];
502
503 auto &base = get<SPIRType>(ops[1]);
504 auto &matrixbase = set<SPIRType>(id);
505
506 matrixbase = base;
507 matrixbase.columns = colcount;
508 matrixbase.self = id;
509 matrixbase.parent_type = ops[1];
510 break;
511 }
512
513 case OpTypeArray:
514 {
515 uint32_t id = ops[0];
516 auto &arraybase = set<SPIRType>(id);
517
518 uint32_t tid = ops[1];
519 auto &base = get<SPIRType>(tid);
520
521 arraybase = base;
522 arraybase.parent_type = tid;
523
524 uint32_t cid = ops[2];
525 ir.mark_used_as_array_length(cid);
526 auto *c = maybe_get<SPIRConstant>(cid);
527 bool literal = c && !c->specialization;
528
529 arraybase.array_size_literal.push_back(literal);
530 arraybase.array.push_back(literal ? c->scalar() : cid);
531 // Do NOT set arraybase.self!
532 break;
533 }
534
535 case OpTypeRuntimeArray:
536 {
537 uint32_t id = ops[0];
538
539 auto &base = get<SPIRType>(ops[1]);
540 auto &arraybase = set<SPIRType>(id);
541
542 arraybase = base;
543 arraybase.array.push_back(0);
544 arraybase.array_size_literal.push_back(true);
545 arraybase.parent_type = ops[1];
546 // Do NOT set arraybase.self!
547 break;
548 }
549
550 case OpTypeImage:
551 {
552 uint32_t id = ops[0];
553 auto &type = set<SPIRType>(id);
554 type.basetype = SPIRType::Image;
555 type.image.type = ops[1];
556 type.image.dim = static_cast<Dim>(ops[2]);
557 type.image.depth = ops[3] == 1;
558 type.image.arrayed = ops[4] != 0;
559 type.image.ms = ops[5] != 0;
560 type.image.sampled = ops[6];
561 type.image.format = static_cast<ImageFormat>(ops[7]);
562 type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
563
564 if (type.image.sampled == 0)
565 SPIRV_CROSS_THROW("OpTypeImage Sampled parameter must not be zero.");
566
567 break;
568 }
569
570 case OpTypeSampledImage:
571 {
572 uint32_t id = ops[0];
573 uint32_t imagetype = ops[1];
574 auto &type = set<SPIRType>(id);
575 type = get<SPIRType>(imagetype);
576 type.basetype = SPIRType::SampledImage;
577 type.self = id;
578 break;
579 }
580
581 case OpTypeSampler:
582 {
583 uint32_t id = ops[0];
584 auto &type = set<SPIRType>(id);
585 type.basetype = SPIRType::Sampler;
586 break;
587 }
588
589 case OpTypePointer:
590 {
591 uint32_t id = ops[0];
592
593 auto &base = get<SPIRType>(ops[2]);
594 auto &ptrbase = set<SPIRType>(id);
595
596 ptrbase = base;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200597 ptrbase.pointer = true;
Hans-Kristian Arntzend0b93722018-11-26 12:23:28 +0100598 ptrbase.pointer_depth++;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200599 ptrbase.storage = static_cast<StorageClass>(ops[1]);
600
601 if (ptrbase.storage == StorageClassAtomicCounter)
602 ptrbase.basetype = SPIRType::AtomicCounter;
603
604 ptrbase.parent_type = ops[2];
605
606 // Do NOT set ptrbase.self!
607 break;
608 }
609
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200610 case OpTypeForwardPointer:
611 {
612 uint32_t id = ops[0];
613 auto &ptrbase = set<SPIRType>(id);
614 ptrbase.pointer = true;
615 ptrbase.pointer_depth++;
616 ptrbase.storage = static_cast<StorageClass>(ops[1]);
617
618 if (ptrbase.storage == StorageClassAtomicCounter)
619 ptrbase.basetype = SPIRType::AtomicCounter;
620
621 break;
622 }
623
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200624 case OpTypeStruct:
625 {
626 uint32_t id = ops[0];
627 auto &type = set<SPIRType>(id);
628 type.basetype = SPIRType::Struct;
629 for (uint32_t i = 1; i < length; i++)
630 type.member_types.push_back(ops[i]);
631
632 // Check if we have seen this struct type before, with just different
633 // decorations.
634 //
635 // Add workaround for issue #17 as well by looking at OpName for the struct
636 // types, which we shouldn't normally do.
637 // We should not normally have to consider type aliases like this to begin with
638 // however ... glslang issues #304, #307 cover this.
639
640 // For stripped names, never consider struct type aliasing.
641 // We risk declaring the same struct multiple times, but type-punning is not allowed
642 // so this is safe.
643 bool consider_aliasing = !ir.get_name(type.self).empty();
644 if (consider_aliasing)
645 {
646 for (auto &other : global_struct_cache)
647 {
648 if (ir.get_name(type.self) == ir.get_name(other) &&
649 types_are_logically_equivalent(type, get<SPIRType>(other)))
650 {
651 type.type_alias = other;
652 break;
653 }
654 }
655
656 if (type.type_alias == 0)
657 global_struct_cache.push_back(id);
658 }
659 break;
660 }
661
662 case OpTypeFunction:
663 {
664 uint32_t id = ops[0];
665 uint32_t ret = ops[1];
666
667 auto &func = set<SPIRFunctionPrototype>(id, ret);
668 for (uint32_t i = 2; i < length; i++)
669 func.parameter_types.push_back(ops[i]);
670 break;
671 }
672
Patrick Moursda39a7b2019-02-26 15:43:03 +0100673 case OpTypeAccelerationStructureNV:
674 {
675 uint32_t id = ops[0];
676 auto &type = set<SPIRType>(id);
677 type.basetype = SPIRType::AccelerationStructureNV;
678 break;
679 }
680
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200681 // Variable declaration
682 // All variables are essentially pointers with a storage qualifier.
683 case OpVariable:
684 {
685 uint32_t type = ops[0];
686 uint32_t id = ops[1];
687 auto storage = static_cast<StorageClass>(ops[2]);
688 uint32_t initializer = length == 4 ? ops[3] : 0;
689
690 if (storage == StorageClassFunction)
691 {
692 if (!current_function)
693 SPIRV_CROSS_THROW("No function currently in scope");
694 current_function->add_local_variable(id);
695 }
696
697 set<SPIRVariable>(id, type, storage, initializer);
698
699 // hlsl based shaders don't have those decorations. force them and then reset when reading/writing images
700 auto &ttype = get<SPIRType>(type);
701 if (ttype.basetype == SPIRType::BaseType::Image)
702 {
703 ir.set_decoration(id, DecorationNonWritable);
704 ir.set_decoration(id, DecorationNonReadable);
705 }
706
707 break;
708 }
709
710 // OpPhi
711 // OpPhi is a fairly magical opcode.
712 // It selects temporary variables based on which parent block we *came from*.
713 // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
714 // variable to emulate SSA Phi.
715 case OpPhi:
716 {
717 if (!current_function)
718 SPIRV_CROSS_THROW("No function currently in scope");
719 if (!current_block)
720 SPIRV_CROSS_THROW("No block currently in scope");
721
722 uint32_t result_type = ops[0];
723 uint32_t id = ops[1];
724
725 // Instead of a temporary, create a new function-wide temporary with this ID instead.
726 auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
727 var.phi_variable = true;
728
729 current_function->add_local_variable(id);
730
731 for (uint32_t i = 2; i + 2 <= length; i += 2)
732 current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
733 break;
734 }
735
736 // Constants
737 case OpSpecConstant:
738 case OpConstant:
739 {
740 uint32_t id = ops[1];
741 auto &type = get<SPIRType>(ops[0]);
742
743 if (type.width > 32)
744 set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
745 else
746 set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
747 break;
748 }
749
750 case OpSpecConstantFalse:
751 case OpConstantFalse:
752 {
753 uint32_t id = ops[1];
754 set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
755 break;
756 }
757
758 case OpSpecConstantTrue:
759 case OpConstantTrue:
760 {
761 uint32_t id = ops[1];
762 set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
763 break;
764 }
765
766 case OpConstantNull:
767 {
768 uint32_t id = ops[1];
769 uint32_t type = ops[0];
770 make_constant_null(id, type);
771 break;
772 }
773
774 case OpSpecConstantComposite:
775 case OpConstantComposite:
776 {
777 uint32_t id = ops[1];
778 uint32_t type = ops[0];
779
780 auto &ctype = get<SPIRType>(type);
781
782 // We can have constants which are structs and arrays.
783 // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
784 // can refer to.
785 if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
786 {
787 set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
788 }
789 else
790 {
791 uint32_t elements = length - 2;
792 if (elements > 4)
793 SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
794
795 SPIRConstant remapped_constant_ops[4];
796 const SPIRConstant *c[4];
797 for (uint32_t i = 0; i < elements; i++)
798 {
799 // Specialization constants operations can also be part of this.
800 // We do not know their value, so any attempt to query SPIRConstant later
801 // will fail. We can only propagate the ID of the expression and use to_expression on it.
802 auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100803 auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200804 if (constant_op)
805 {
806 if (op == OpConstantComposite)
807 SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
808
809 remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
810 remapped_constant_ops[i].self = constant_op->self;
811 remapped_constant_ops[i].constant_type = constant_op->basetype;
812 remapped_constant_ops[i].specialization = true;
813 c[i] = &remapped_constant_ops[i];
814 }
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100815 else if (undef_op)
816 {
817 // Undefined, just pick 0.
818 remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
819 remapped_constant_ops[i].constant_type = undef_op->basetype;
820 c[i] = &remapped_constant_ops[i];
821 }
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200822 else
823 c[i] = &get<SPIRConstant>(ops[2 + i]);
824 }
825 set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
826 }
827 break;
828 }
829
830 // Functions
831 case OpFunction:
832 {
833 uint32_t res = ops[0];
834 uint32_t id = ops[1];
835 // Control
836 uint32_t type = ops[3];
837
838 if (current_function)
839 SPIRV_CROSS_THROW("Must end a function before starting a new one!");
840
841 current_function = &set<SPIRFunction>(id, res, type);
842 break;
843 }
844
845 case OpFunctionParameter:
846 {
847 uint32_t type = ops[0];
848 uint32_t id = ops[1];
849
850 if (!current_function)
851 SPIRV_CROSS_THROW("Must be in a function!");
852
853 current_function->add_parameter(type, id);
854 set<SPIRVariable>(id, type, StorageClassFunction);
855 break;
856 }
857
858 case OpFunctionEnd:
859 {
860 if (current_block)
861 {
862 // Very specific error message, but seems to come up quite often.
863 SPIRV_CROSS_THROW(
864 "Cannot end a function before ending the current block.\n"
865 "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
866 }
867 current_function = nullptr;
868 break;
869 }
870
871 // Blocks
872 case OpLabel:
873 {
874 // OpLabel always starts a block.
875 if (!current_function)
876 SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
877
878 uint32_t id = ops[0];
879
880 current_function->blocks.push_back(id);
881 if (!current_function->entry_block)
882 current_function->entry_block = id;
883
884 if (current_block)
885 SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
886
887 current_block = &set<SPIRBlock>(id);
888 break;
889 }
890
891 // Branch instructions end blocks.
892 case OpBranch:
893 {
894 if (!current_block)
895 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
896
897 uint32_t target = ops[0];
898 current_block->terminator = SPIRBlock::Direct;
899 current_block->next_block = target;
900 current_block = nullptr;
901 break;
902 }
903
904 case OpBranchConditional:
905 {
906 if (!current_block)
907 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
908
909 current_block->condition = ops[0];
910 current_block->true_block = ops[1];
911 current_block->false_block = ops[2];
912
913 current_block->terminator = SPIRBlock::Select;
914 current_block = nullptr;
915 break;
916 }
917
918 case OpSwitch:
919 {
920 if (!current_block)
921 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
922
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200923 current_block->terminator = SPIRBlock::MultiSelect;
924
925 current_block->condition = ops[0];
926 current_block->default_block = ops[1];
927
928 for (uint32_t i = 2; i + 2 <= length; i += 2)
929 current_block->cases.push_back({ ops[i], ops[i + 1] });
930
931 // If we jump to next block, make it break instead since we're inside a switch case block at that point.
932 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
933
934 current_block = nullptr;
935 break;
936 }
937
938 case OpKill:
939 {
940 if (!current_block)
941 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
942 current_block->terminator = SPIRBlock::Kill;
943 current_block = nullptr;
944 break;
945 }
946
947 case OpReturn:
948 {
949 if (!current_block)
950 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
951 current_block->terminator = SPIRBlock::Return;
952 current_block = nullptr;
953 break;
954 }
955
956 case OpReturnValue:
957 {
958 if (!current_block)
959 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
960 current_block->terminator = SPIRBlock::Return;
961 current_block->return_value = ops[0];
962 current_block = nullptr;
963 break;
964 }
965
966 case OpUnreachable:
967 {
968 if (!current_block)
969 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
970 current_block->terminator = SPIRBlock::Unreachable;
971 current_block = nullptr;
972 break;
973 }
974
975 case OpSelectionMerge:
976 {
977 if (!current_block)
978 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
979
980 current_block->next_block = ops[0];
981 current_block->merge = SPIRBlock::MergeSelection;
982 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
983
984 if (length >= 2)
985 {
986 if (ops[1] & SelectionControlFlattenMask)
987 current_block->hint = SPIRBlock::HintFlatten;
988 else if (ops[1] & SelectionControlDontFlattenMask)
989 current_block->hint = SPIRBlock::HintDontFlatten;
990 }
991 break;
992 }
993
994 case OpLoopMerge:
995 {
996 if (!current_block)
997 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
998
999 current_block->merge_block = ops[0];
1000 current_block->continue_block = ops[1];
1001 current_block->merge = SPIRBlock::MergeLoop;
1002
1003 ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
1004 ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1005
1006 ir.continue_block_to_loop_header[current_block->continue_block] = current_block->self;
1007
1008 // Don't add loop headers to continue blocks,
1009 // which would make it impossible branch into the loop header since
1010 // they are treated as continues.
1011 if (current_block->continue_block != current_block->self)
1012 ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
1013
1014 if (length >= 3)
1015 {
1016 if (ops[2] & LoopControlUnrollMask)
1017 current_block->hint = SPIRBlock::HintUnroll;
1018 else if (ops[2] & LoopControlDontUnrollMask)
1019 current_block->hint = SPIRBlock::HintDontUnroll;
1020 }
1021 break;
1022 }
1023
1024 case OpSpecConstantOp:
1025 {
1026 if (length < 3)
1027 SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
1028
1029 uint32_t result_type = ops[0];
1030 uint32_t id = ops[1];
1031 auto spec_op = static_cast<Op>(ops[2]);
1032
1033 set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
1034 break;
1035 }
1036
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001037 case OpLine:
1038 {
1039 // OpLine might come at global scope, but we don't care about those since they will not be declared in any
1040 // meaningful correct order.
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001041 // Ignore all OpLine directives which live outside a function.
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001042 if (current_block)
1043 current_block->ops.push_back(instruction);
1044
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001045 // Line directives may arrive before first OpLabel.
1046 // Treat this as the line of the function declaration,
1047 // so warnings for arguments can propagate properly.
1048 if (current_function)
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001049 {
1050 // Store the first one we find and emit it before creating the function prototype.
1051 if (current_function->entry_line.file_id == 0)
1052 {
1053 current_function->entry_line.file_id = ops[0];
1054 current_function->entry_line.line_literal = ops[1];
1055 }
1056 }
1057 break;
1058 }
1059
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001060 // Actual opcodes.
1061 default:
1062 {
1063 if (!current_block)
1064 SPIRV_CROSS_THROW("Currently no block to insert opcode.");
1065
1066 current_block->ops.push_back(instruction);
1067 break;
1068 }
1069 }
1070}
1071
1072bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
1073{
1074 if (a.basetype != b.basetype)
1075 return false;
1076 if (a.width != b.width)
1077 return false;
1078 if (a.vecsize != b.vecsize)
1079 return false;
1080 if (a.columns != b.columns)
1081 return false;
1082 if (a.array.size() != b.array.size())
1083 return false;
1084
1085 size_t array_count = a.array.size();
1086 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
1087 return false;
1088
1089 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
1090 {
1091 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
1092 return false;
1093 }
1094
1095 if (a.member_types.size() != b.member_types.size())
1096 return false;
1097
1098 size_t member_types = a.member_types.size();
1099 for (size_t i = 0; i < member_types; i++)
1100 {
1101 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
1102 return false;
1103 }
1104
1105 return true;
1106}
1107
1108bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
1109{
1110 auto &type = get<SPIRType>(v.basetype);
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001111
1112 auto *type_meta = ir.find_meta(type.self);
1113
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001114 bool ssbo = v.storage == StorageClassStorageBuffer ||
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001115 (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001116 bool image = type.basetype == SPIRType::Image;
1117 bool counter = type.basetype == SPIRType::AtomicCounter;
1118
1119 bool is_restrict;
1120 if (ssbo)
1121 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
1122 else
1123 is_restrict = ir.has_decoration(v.self, DecorationRestrict);
1124
1125 return !is_restrict && (ssbo || image || counter);
1126}
1127
1128void Parser::make_constant_null(uint32_t id, uint32_t type)
1129{
1130 auto &constant_type = get<SPIRType>(type);
1131
Chip Davis3bfb2f92018-12-03 02:06:33 -06001132 if (constant_type.pointer)
1133 {
1134 auto &constant = set<SPIRConstant>(id, type);
1135 constant.make_null(constant_type);
1136 }
1137 else if (!constant_type.array.empty())
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001138 {
1139 assert(constant_type.parent_type);
1140 uint32_t parent_id = ir.increase_bound_by(1);
1141 make_constant_null(parent_id, constant_type.parent_type);
1142
1143 if (!constant_type.array_size_literal.back())
1144 SPIRV_CROSS_THROW("Array size of OpConstantNull must be a literal.");
1145
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001146 SmallVector<uint32_t> elements(constant_type.array.back());
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001147 for (uint32_t i = 0; i < constant_type.array.back(); i++)
1148 elements[i] = parent_id;
1149 set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
1150 }
1151 else if (!constant_type.member_types.empty())
1152 {
1153 uint32_t member_ids = ir.increase_bound_by(uint32_t(constant_type.member_types.size()));
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001154 SmallVector<uint32_t> elements(constant_type.member_types.size());
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001155 for (uint32_t i = 0; i < constant_type.member_types.size(); i++)
1156 {
1157 make_constant_null(member_ids + i, constant_type.member_types[i]);
1158 elements[i] = member_ids + i;
1159 }
1160 set<SPIRConstant>(id, type, elements.data(), uint32_t(elements.size()), false);
1161 }
1162 else
1163 {
1164 auto &constant = set<SPIRConstant>(id, type);
1165 constant.make_null(constant_type);
1166 }
1167}
1168
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001169} // namespace SPIRV_CROSS_NAMESPACE