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