blob: 92db5287aba1aa293367513d96506a0807d92a65 [file] [log] [blame]
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001/*
Hans-Kristian Arntzenf9818f02020-01-16 15:24:37 +01002 * Copyright 2018-2020 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 Arntzen02c34fe2019-09-19 10:26:04 +020063 case 0x10500: // SPIR-V 1.5
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020064 return true;
65
66 default:
67 return false;
68 }
69}
70
71void Parser::parse()
72{
73 auto &spirv = ir.spirv;
74
75 auto len = spirv.size();
76 if (len < 5)
77 SPIRV_CROSS_THROW("SPIRV file too small.");
78
79 auto s = spirv.data();
80
81 // Endian-swap if we need to.
82 if (s[0] == swap_endian(MagicNumber))
83 transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
84
85 if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
86 SPIRV_CROSS_THROW("Invalid SPIRV format.");
87
88 uint32_t bound = s[3];
Hans-Kristian Arntzen92a42942020-02-14 12:57:01 +010089
90 const uint32_t MaximumNumberOfIDs = 0x3fffff;
91 if (bound > MaximumNumberOfIDs)
92 SPIRV_CROSS_THROW("ID bound exceeds limit of 0x3fffff.\n");
93
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020094 ir.set_id_bounds(bound);
95
96 uint32_t offset = 5;
97
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +020098 SmallVector<Instruction> instructions;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +020099 while (offset < len)
100 {
101 Instruction instr = {};
102 instr.op = spirv[offset] & 0xffff;
103 instr.count = (spirv[offset] >> 16) & 0xffff;
104
105 if (instr.count == 0)
106 SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
107
108 instr.offset = offset + 1;
109 instr.length = instr.count - 1;
110
111 offset += instr.count;
112
113 if (offset > spirv.size())
114 SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
115
116 instructions.push_back(instr);
117 }
118
119 for (auto &i : instructions)
120 parse(i);
121
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200122 for (auto &fixup : forward_pointer_fixups)
123 {
124 auto &target = get<SPIRType>(fixup.first);
125 auto &source = get<SPIRType>(fixup.second);
126 target.member_types = source.member_types;
127 target.basetype = source.basetype;
128 target.self = source.self;
129 }
130 forward_pointer_fixups.clear();
131
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200132 if (current_function)
133 SPIRV_CROSS_THROW("Function was not terminated.");
134 if (current_block)
135 SPIRV_CROSS_THROW("Block was not terminated.");
136}
137
138const uint32_t *Parser::stream(const Instruction &instr) const
139{
140 // If we're not going to use any arguments, just return nullptr.
141 // We want to avoid case where we return an out of range pointer
142 // that trips debug assertions on some platforms.
143 if (!instr.length)
144 return nullptr;
145
146 if (instr.offset + instr.length > ir.spirv.size())
147 SPIRV_CROSS_THROW("Compiler::stream() out of range.");
148 return &ir.spirv[instr.offset];
149}
150
Hans-Kristian Arntzen3fe57d32019-04-09 12:46:23 +0200151static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200152{
153 string ret;
154 for (uint32_t i = offset; i < spirv.size(); i++)
155 {
156 uint32_t w = spirv[i];
157
158 for (uint32_t j = 0; j < 4; j++, w >>= 8)
159 {
160 char c = w & 0xff;
161 if (c == '\0')
162 return ret;
163 ret += c;
164 }
165 }
166
167 SPIRV_CROSS_THROW("String was not terminated before EOF");
168}
169
170void Parser::parse(const Instruction &instruction)
171{
172 auto *ops = stream(instruction);
173 auto op = static_cast<Op>(instruction.op);
174 uint32_t length = instruction.length;
175
176 switch (op)
177 {
lifpan00a765e2018-11-15 09:04:36 +0800178 case OpSourceContinued:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200179 case OpSourceExtension:
180 case OpNop:
lifpan91610962018-11-13 14:28:38 +0800181 case OpModuleProcessed:
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200182 break;
183
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +0200184 case OpString:
185 {
186 set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
187 break;
188 }
189
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200190 case OpMemoryModel:
191 ir.addressing_model = static_cast<AddressingModel>(ops[0]);
192 ir.memory_model = static_cast<MemoryModel>(ops[1]);
193 break;
194
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200195 case OpSource:
196 {
197 auto lang = static_cast<SourceLanguage>(ops[0]);
198 switch (lang)
199 {
200 case SourceLanguageESSL:
201 ir.source.es = true;
202 ir.source.version = ops[1];
203 ir.source.known = true;
204 ir.source.hlsl = false;
205 break;
206
207 case SourceLanguageGLSL:
208 ir.source.es = false;
209 ir.source.version = ops[1];
210 ir.source.known = true;
211 ir.source.hlsl = false;
212 break;
213
214 case SourceLanguageHLSL:
215 // For purposes of cross-compiling, this is GLSL 450.
216 ir.source.es = false;
217 ir.source.version = 450;
218 ir.source.known = true;
219 ir.source.hlsl = true;
220 break;
221
222 default:
223 ir.source.known = false;
224 break;
225 }
226 break;
227 }
228
229 case OpUndef:
230 {
231 uint32_t result_type = ops[0];
232 uint32_t id = ops[1];
233 set<SPIRUndef>(id, result_type);
lifpan876627d2019-04-08 19:45:31 +0800234 if (current_block)
235 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200236 break;
237 }
238
239 case OpCapability:
240 {
241 uint32_t cap = ops[0];
242 if (cap == CapabilityKernel)
243 SPIRV_CROSS_THROW("Kernel capability not supported.");
244
245 ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
246 break;
247 }
248
249 case OpExtension:
250 {
251 auto ext = extract_string(ir.spirv, instruction.offset);
252 ir.declared_extensions.push_back(move(ext));
253 break;
254 }
255
256 case OpExtInstImport:
257 {
258 uint32_t id = ops[0];
259 auto ext = extract_string(ir.spirv, instruction.offset + 1);
260 if (ext == "GLSL.std.450")
261 set<SPIRExtension>(id, SPIRExtension::GLSL);
Lifeng Pan5ca87792019-07-04 16:03:06 +0800262 else if (ext == "DebugInfo")
263 set<SPIRExtension>(id, SPIRExtension::SPV_debug_info);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200264 else if (ext == "SPV_AMD_shader_ballot")
265 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
266 else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
267 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
268 else if (ext == "SPV_AMD_shader_trinary_minmax")
269 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
270 else if (ext == "SPV_AMD_gcn_shader")
271 set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
272 else
273 set<SPIRExtension>(id, SPIRExtension::Unsupported);
274
275 // Other SPIR-V extensions which have ExtInstrs are currently not supported.
276
277 break;
278 }
279
Lifeng Pan5ca87792019-07-04 16:03:06 +0800280 case OpExtInst:
281 {
282 // The SPIR-V debug information extended instructions might come at global scope.
283 if (current_block)
284 current_block->ops.push_back(instruction);
285 break;
286 }
287
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200288 case OpEntryPoint:
289 {
290 auto itr =
291 ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
292 extract_string(ir.spirv, instruction.offset + 2))));
293 auto &e = itr.first->second;
294
295 // Strings need nul-terminator and consume the whole word.
296 uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +0200297
298 for (uint32_t i = strlen_words + 2; i < instruction.length; i++)
299 e.interface_variables.push_back(ops[i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200300
301 // Set the name of the entry point in case OpName is not provided later.
302 ir.set_name(ops[1], e.name);
303
304 // If we don't have an entry, make the first one our "default".
305 if (!ir.default_entry_point)
306 ir.default_entry_point = ops[1];
307 break;
308 }
309
310 case OpExecutionMode:
311 {
312 auto &execution = ir.entry_points[ops[0]];
313 auto mode = static_cast<ExecutionMode>(ops[1]);
314 execution.flags.set(mode);
315
316 switch (mode)
317 {
318 case ExecutionModeInvocations:
319 execution.invocations = ops[2];
320 break;
321
322 case ExecutionModeLocalSize:
323 execution.workgroup_size.x = ops[2];
324 execution.workgroup_size.y = ops[3];
325 execution.workgroup_size.z = ops[4];
326 break;
327
328 case ExecutionModeOutputVertices:
329 execution.output_vertices = ops[2];
330 break;
331
332 default:
333 break;
334 }
335 break;
336 }
337
338 case OpName:
339 {
340 uint32_t id = ops[0];
341 ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
342 break;
343 }
344
345 case OpMemberName:
346 {
347 uint32_t id = ops[0];
348 uint32_t member = ops[1];
349 ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
350 break;
351 }
352
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100353 case OpDecorationGroup:
354 {
355 // Noop, this simply means an ID should be a collector of decorations.
356 // The meta array is already a flat array of decorations which will contain the relevant decorations.
357 break;
358 }
359
360 case OpGroupDecorate:
361 {
362 uint32_t group_id = ops[0];
363 auto &decorations = ir.meta[group_id].decoration;
364 auto &flags = decorations.decoration_flags;
365
366 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
367 // i.e., we cannot just copy the meta structure directly.
368 for (uint32_t i = 1; i < length; i++)
369 {
370 uint32_t target = ops[i];
371 flags.for_each_bit([&](uint32_t bit) {
372 auto decoration = static_cast<Decoration>(bit);
373
374 if (decoration_is_string(decoration))
375 {
376 ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
377 }
378 else
379 {
380 ir.meta[target].decoration_word_offset[decoration] =
381 ir.meta[group_id].decoration_word_offset[decoration];
382 ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
383 }
384 });
385 }
386 break;
387 }
388
389 case OpGroupMemberDecorate:
390 {
391 uint32_t group_id = ops[0];
392 auto &flags = ir.meta[group_id].decoration.decoration_flags;
393
394 // Copies decorations from one ID to another. Only copy decorations which are set in the group,
395 // i.e., we cannot just copy the meta structure directly.
396 for (uint32_t i = 1; i + 1 < length; i += 2)
397 {
398 uint32_t target = ops[i + 0];
399 uint32_t index = ops[i + 1];
400 flags.for_each_bit([&](uint32_t bit) {
401 auto decoration = static_cast<Decoration>(bit);
402
403 if (decoration_is_string(decoration))
404 ir.set_member_decoration_string(target, index, decoration,
405 ir.get_decoration_string(group_id, decoration));
406 else
407 ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
408 });
409 }
410 break;
411 }
412
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200413 case OpDecorate:
414 case OpDecorateId:
415 {
Hans-Kristian Arntzenfa42ed32018-11-15 10:51:01 +0100416 // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
417 // so merge decorate and decorate-id here.
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200418 uint32_t id = ops[0];
419
420 auto decoration = static_cast<Decoration>(ops[1]);
421 if (length >= 3)
422 {
423 ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
424 ir.set_decoration(id, decoration, ops[2]);
425 }
426 else
427 ir.set_decoration(id, decoration);
428
429 break;
430 }
431
432 case OpDecorateStringGOOGLE:
433 {
434 uint32_t id = ops[0];
435 auto decoration = static_cast<Decoration>(ops[1]);
436 ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
437 break;
438 }
439
440 case OpMemberDecorate:
441 {
442 uint32_t id = ops[0];
443 uint32_t member = ops[1];
444 auto decoration = static_cast<Decoration>(ops[2]);
445 if (length >= 4)
446 ir.set_member_decoration(id, member, decoration, ops[3]);
447 else
448 ir.set_member_decoration(id, member, decoration);
449 break;
450 }
451
452 case OpMemberDecorateStringGOOGLE:
453 {
454 uint32_t id = ops[0];
455 uint32_t member = ops[1];
456 auto decoration = static_cast<Decoration>(ops[2]);
457 ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
458 break;
459 }
460
461 // Build up basic types.
462 case OpTypeVoid:
463 {
464 uint32_t id = ops[0];
465 auto &type = set<SPIRType>(id);
466 type.basetype = SPIRType::Void;
467 break;
468 }
469
470 case OpTypeBool:
471 {
472 uint32_t id = ops[0];
473 auto &type = set<SPIRType>(id);
474 type.basetype = SPIRType::Boolean;
475 type.width = 1;
476 break;
477 }
478
479 case OpTypeFloat:
480 {
481 uint32_t id = ops[0];
482 uint32_t width = ops[1];
483 auto &type = set<SPIRType>(id);
484 if (width == 64)
485 type.basetype = SPIRType::Double;
486 else if (width == 32)
487 type.basetype = SPIRType::Float;
488 else if (width == 16)
489 type.basetype = SPIRType::Half;
490 else
491 SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
492 type.width = width;
493 break;
494 }
495
496 case OpTypeInt:
497 {
498 uint32_t id = ops[0];
499 uint32_t width = ops[1];
lifpanb21525b2018-11-28 14:20:24 +0800500 bool signedness = ops[2] != 0;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200501 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen2ed171e2019-01-30 14:49:55 +0100502 type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200503 type.width = width;
504 break;
505 }
506
507 // Build composite types by "inheriting".
508 // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
509 // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
510 case OpTypeVector:
511 {
512 uint32_t id = ops[0];
513 uint32_t vecsize = ops[2];
514
515 auto &base = get<SPIRType>(ops[1]);
516 auto &vecbase = set<SPIRType>(id);
517
518 vecbase = base;
519 vecbase.vecsize = vecsize;
520 vecbase.self = id;
521 vecbase.parent_type = ops[1];
522 break;
523 }
524
525 case OpTypeMatrix:
526 {
527 uint32_t id = ops[0];
528 uint32_t colcount = ops[2];
529
530 auto &base = get<SPIRType>(ops[1]);
531 auto &matrixbase = set<SPIRType>(id);
532
533 matrixbase = base;
534 matrixbase.columns = colcount;
535 matrixbase.self = id;
536 matrixbase.parent_type = ops[1];
537 break;
538 }
539
540 case OpTypeArray:
541 {
542 uint32_t id = ops[0];
543 auto &arraybase = set<SPIRType>(id);
544
545 uint32_t tid = ops[1];
546 auto &base = get<SPIRType>(tid);
547
548 arraybase = base;
549 arraybase.parent_type = tid;
550
551 uint32_t cid = ops[2];
552 ir.mark_used_as_array_length(cid);
553 auto *c = maybe_get<SPIRConstant>(cid);
554 bool literal = c && !c->specialization;
555
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200556 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
557 // references.
558 if (base.forward_pointer)
559 forward_pointer_fixups.push_back({ id, tid });
560
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200561 arraybase.array_size_literal.push_back(literal);
562 arraybase.array.push_back(literal ? c->scalar() : cid);
563 // Do NOT set arraybase.self!
564 break;
565 }
566
567 case OpTypeRuntimeArray:
568 {
569 uint32_t id = ops[0];
570
571 auto &base = get<SPIRType>(ops[1]);
572 auto &arraybase = set<SPIRType>(id);
573
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200574 // We're copying type information into Array types, so we'll need a fixup for any physical pointer
575 // references.
576 if (base.forward_pointer)
577 forward_pointer_fixups.push_back({ id, ops[1] });
578
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200579 arraybase = base;
580 arraybase.array.push_back(0);
581 arraybase.array_size_literal.push_back(true);
582 arraybase.parent_type = ops[1];
583 // Do NOT set arraybase.self!
584 break;
585 }
586
587 case OpTypeImage:
588 {
589 uint32_t id = ops[0];
590 auto &type = set<SPIRType>(id);
591 type.basetype = SPIRType::Image;
592 type.image.type = ops[1];
593 type.image.dim = static_cast<Dim>(ops[2]);
594 type.image.depth = ops[3] == 1;
595 type.image.arrayed = ops[4] != 0;
596 type.image.ms = ops[5] != 0;
597 type.image.sampled = ops[6];
598 type.image.format = static_cast<ImageFormat>(ops[7]);
599 type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200600 break;
601 }
602
603 case OpTypeSampledImage:
604 {
605 uint32_t id = ops[0];
606 uint32_t imagetype = ops[1];
607 auto &type = set<SPIRType>(id);
608 type = get<SPIRType>(imagetype);
609 type.basetype = SPIRType::SampledImage;
610 type.self = id;
611 break;
612 }
613
614 case OpTypeSampler:
615 {
616 uint32_t id = ops[0];
617 auto &type = set<SPIRType>(id);
618 type.basetype = SPIRType::Sampler;
619 break;
620 }
621
622 case OpTypePointer:
623 {
624 uint32_t id = ops[0];
625
Hans-Kristian Arntzen1f018b02020-11-03 10:51:56 +0100626 // Very rarely, we might receive a FunctionPrototype here.
627 // We won't be able to compile it, but we shouldn't crash when parsing.
628 // We should be able to reflect.
629 auto *base = maybe_get<SPIRType>(ops[2]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200630 auto &ptrbase = set<SPIRType>(id);
631
Hans-Kristian Arntzen1f018b02020-11-03 10:51:56 +0100632 if (base)
633 ptrbase = *base;
634
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200635 ptrbase.pointer = true;
Hans-Kristian Arntzend0b93722018-11-26 12:23:28 +0100636 ptrbase.pointer_depth++;
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200637 ptrbase.storage = static_cast<StorageClass>(ops[1]);
638
639 if (ptrbase.storage == StorageClassAtomicCounter)
640 ptrbase.basetype = SPIRType::AtomicCounter;
641
Hans-Kristian Arntzen1f018b02020-11-03 10:51:56 +0100642 if (base && base->forward_pointer)
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200643 forward_pointer_fixups.push_back({ id, ops[2] });
644
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200645 ptrbase.parent_type = ops[2];
646
647 // Do NOT set ptrbase.self!
648 break;
649 }
650
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200651 case OpTypeForwardPointer:
652 {
653 uint32_t id = ops[0];
654 auto &ptrbase = set<SPIRType>(id);
655 ptrbase.pointer = true;
656 ptrbase.pointer_depth++;
657 ptrbase.storage = static_cast<StorageClass>(ops[1]);
Hans-Kristian Arntzen58dad822020-05-25 11:05:42 +0200658 ptrbase.forward_pointer = true;
Hans-Kristian Arntzen2cc374a2019-04-24 14:12:50 +0200659
660 if (ptrbase.storage == StorageClassAtomicCounter)
661 ptrbase.basetype = SPIRType::AtomicCounter;
662
663 break;
664 }
665
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200666 case OpTypeStruct:
667 {
668 uint32_t id = ops[0];
669 auto &type = set<SPIRType>(id);
670 type.basetype = SPIRType::Struct;
671 for (uint32_t i = 1; i < length; i++)
672 type.member_types.push_back(ops[i]);
673
674 // Check if we have seen this struct type before, with just different
675 // decorations.
676 //
677 // Add workaround for issue #17 as well by looking at OpName for the struct
678 // types, which we shouldn't normally do.
679 // We should not normally have to consider type aliases like this to begin with
680 // however ... glslang issues #304, #307 cover this.
681
682 // For stripped names, never consider struct type aliasing.
683 // We risk declaring the same struct multiple times, but type-punning is not allowed
684 // so this is safe.
685 bool consider_aliasing = !ir.get_name(type.self).empty();
686 if (consider_aliasing)
687 {
688 for (auto &other : global_struct_cache)
689 {
690 if (ir.get_name(type.self) == ir.get_name(other) &&
691 types_are_logically_equivalent(type, get<SPIRType>(other)))
692 {
693 type.type_alias = other;
694 break;
695 }
696 }
697
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +0200698 if (type.type_alias == TypeID(0))
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200699 global_struct_cache.push_back(id);
700 }
701 break;
702 }
703
704 case OpTypeFunction:
705 {
706 uint32_t id = ops[0];
707 uint32_t ret = ops[1];
708
709 auto &func = set<SPIRFunctionPrototype>(id, ret);
710 for (uint32_t i = 2; i < length; i++)
711 func.parameter_types.push_back(ops[i]);
712 break;
713 }
714
Hans-Kristian Arntzen6b0e5582020-04-21 14:25:18 +0200715 case OpTypeAccelerationStructureKHR:
Patrick Moursda39a7b2019-02-26 15:43:03 +0100716 {
717 uint32_t id = ops[0];
718 auto &type = set<SPIRType>(id);
Hans-Kristian Arntzen6b0e5582020-04-21 14:25:18 +0200719 type.basetype = SPIRType::AccelerationStructure;
720 break;
721 }
722
723 case OpTypeRayQueryProvisionalKHR:
724 {
725 uint32_t id = ops[0];
726 auto &type = set<SPIRType>(id);
727 type.basetype = SPIRType::RayQuery;
Patrick Moursda39a7b2019-02-26 15:43:03 +0100728 break;
729 }
730
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200731 // Variable declaration
732 // All variables are essentially pointers with a storage qualifier.
733 case OpVariable:
734 {
735 uint32_t type = ops[0];
736 uint32_t id = ops[1];
737 auto storage = static_cast<StorageClass>(ops[2]);
738 uint32_t initializer = length == 4 ? ops[3] : 0;
739
740 if (storage == StorageClassFunction)
741 {
742 if (!current_function)
743 SPIRV_CROSS_THROW("No function currently in scope");
744 current_function->add_local_variable(id);
745 }
746
747 set<SPIRVariable>(id, type, storage, initializer);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200748 break;
749 }
750
751 // OpPhi
752 // OpPhi is a fairly magical opcode.
753 // It selects temporary variables based on which parent block we *came from*.
754 // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
755 // variable to emulate SSA Phi.
756 case OpPhi:
757 {
758 if (!current_function)
759 SPIRV_CROSS_THROW("No function currently in scope");
760 if (!current_block)
761 SPIRV_CROSS_THROW("No block currently in scope");
762
763 uint32_t result_type = ops[0];
764 uint32_t id = ops[1];
765
766 // Instead of a temporary, create a new function-wide temporary with this ID instead.
767 auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
768 var.phi_variable = true;
769
770 current_function->add_local_variable(id);
771
772 for (uint32_t i = 2; i + 2 <= length; i += 2)
773 current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
774 break;
775 }
776
777 // Constants
778 case OpSpecConstant:
779 case OpConstant:
780 {
781 uint32_t id = ops[1];
782 auto &type = get<SPIRType>(ops[0]);
783
784 if (type.width > 32)
785 set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
786 else
787 set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
788 break;
789 }
790
791 case OpSpecConstantFalse:
792 case OpConstantFalse:
793 {
794 uint32_t id = ops[1];
795 set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
796 break;
797 }
798
799 case OpSpecConstantTrue:
800 case OpConstantTrue:
801 {
802 uint32_t id = ops[1];
803 set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
804 break;
805 }
806
807 case OpConstantNull:
808 {
809 uint32_t id = ops[1];
810 uint32_t type = ops[0];
Hans-Kristian Arntzenb8905bb2020-03-26 11:21:23 +0100811 ir.make_constant_null(id, type, true);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200812 break;
813 }
814
815 case OpSpecConstantComposite:
816 case OpConstantComposite:
817 {
818 uint32_t id = ops[1];
819 uint32_t type = ops[0];
820
821 auto &ctype = get<SPIRType>(type);
822
823 // We can have constants which are structs and arrays.
824 // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
825 // can refer to.
826 if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
827 {
828 set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
829 }
830 else
831 {
832 uint32_t elements = length - 2;
833 if (elements > 4)
834 SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
835
836 SPIRConstant remapped_constant_ops[4];
837 const SPIRConstant *c[4];
838 for (uint32_t i = 0; i < elements; i++)
839 {
840 // Specialization constants operations can also be part of this.
841 // We do not know their value, so any attempt to query SPIRConstant later
842 // will fail. We can only propagate the ID of the expression and use to_expression on it.
843 auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100844 auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200845 if (constant_op)
846 {
847 if (op == OpConstantComposite)
848 SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
849
850 remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
851 remapped_constant_ops[i].self = constant_op->self;
852 remapped_constant_ops[i].constant_type = constant_op->basetype;
853 remapped_constant_ops[i].specialization = true;
854 c[i] = &remapped_constant_ops[i];
855 }
Hans-Kristian Arntzendf3e21a2019-03-27 10:51:23 +0100856 else if (undef_op)
857 {
858 // Undefined, just pick 0.
859 remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
860 remapped_constant_ops[i].constant_type = undef_op->basetype;
861 c[i] = &remapped_constant_ops[i];
862 }
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200863 else
864 c[i] = &get<SPIRConstant>(ops[2 + i]);
865 }
866 set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
867 }
868 break;
869 }
870
871 // Functions
872 case OpFunction:
873 {
874 uint32_t res = ops[0];
875 uint32_t id = ops[1];
876 // Control
877 uint32_t type = ops[3];
878
879 if (current_function)
880 SPIRV_CROSS_THROW("Must end a function before starting a new one!");
881
882 current_function = &set<SPIRFunction>(id, res, type);
883 break;
884 }
885
886 case OpFunctionParameter:
887 {
888 uint32_t type = ops[0];
889 uint32_t id = ops[1];
890
891 if (!current_function)
892 SPIRV_CROSS_THROW("Must be in a function!");
893
894 current_function->add_parameter(type, id);
895 set<SPIRVariable>(id, type, StorageClassFunction);
896 break;
897 }
898
899 case OpFunctionEnd:
900 {
901 if (current_block)
902 {
903 // Very specific error message, but seems to come up quite often.
904 SPIRV_CROSS_THROW(
905 "Cannot end a function before ending the current block.\n"
906 "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
907 }
908 current_function = nullptr;
909 break;
910 }
911
912 // Blocks
913 case OpLabel:
914 {
915 // OpLabel always starts a block.
916 if (!current_function)
917 SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
918
919 uint32_t id = ops[0];
920
921 current_function->blocks.push_back(id);
922 if (!current_function->entry_block)
923 current_function->entry_block = id;
924
925 if (current_block)
926 SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
927
928 current_block = &set<SPIRBlock>(id);
929 break;
930 }
931
932 // Branch instructions end blocks.
933 case OpBranch:
934 {
935 if (!current_block)
936 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
937
938 uint32_t target = ops[0];
939 current_block->terminator = SPIRBlock::Direct;
940 current_block->next_block = target;
941 current_block = nullptr;
942 break;
943 }
944
945 case OpBranchConditional:
946 {
947 if (!current_block)
948 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
949
950 current_block->condition = ops[0];
951 current_block->true_block = ops[1];
952 current_block->false_block = ops[2];
953
954 current_block->terminator = SPIRBlock::Select;
955 current_block = nullptr;
956 break;
957 }
958
959 case OpSwitch:
960 {
961 if (!current_block)
962 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
963
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +0200964 current_block->terminator = SPIRBlock::MultiSelect;
965
966 current_block->condition = ops[0];
967 current_block->default_block = ops[1];
968
969 for (uint32_t i = 2; i + 2 <= length; i += 2)
970 current_block->cases.push_back({ ops[i], ops[i + 1] });
971
972 // If we jump to next block, make it break instead since we're inside a switch case block at that point.
973 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
974
975 current_block = nullptr;
976 break;
977 }
978
979 case OpKill:
980 {
981 if (!current_block)
982 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
983 current_block->terminator = SPIRBlock::Kill;
984 current_block = nullptr;
985 break;
986 }
987
988 case OpReturn:
989 {
990 if (!current_block)
991 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
992 current_block->terminator = SPIRBlock::Return;
993 current_block = nullptr;
994 break;
995 }
996
997 case OpReturnValue:
998 {
999 if (!current_block)
1000 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1001 current_block->terminator = SPIRBlock::Return;
1002 current_block->return_value = ops[0];
1003 current_block = nullptr;
1004 break;
1005 }
1006
1007 case OpUnreachable:
1008 {
1009 if (!current_block)
1010 SPIRV_CROSS_THROW("Trying to end a non-existing block.");
1011 current_block->terminator = SPIRBlock::Unreachable;
1012 current_block = nullptr;
1013 break;
1014 }
1015
1016 case OpSelectionMerge:
1017 {
1018 if (!current_block)
1019 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1020
1021 current_block->next_block = ops[0];
1022 current_block->merge = SPIRBlock::MergeSelection;
1023 ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
1024
1025 if (length >= 2)
1026 {
1027 if (ops[1] & SelectionControlFlattenMask)
1028 current_block->hint = SPIRBlock::HintFlatten;
1029 else if (ops[1] & SelectionControlDontFlattenMask)
1030 current_block->hint = SPIRBlock::HintDontFlatten;
1031 }
1032 break;
1033 }
1034
1035 case OpLoopMerge:
1036 {
1037 if (!current_block)
1038 SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
1039
1040 current_block->merge_block = ops[0];
1041 current_block->continue_block = ops[1];
1042 current_block->merge = SPIRBlock::MergeLoop;
1043
1044 ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
1045 ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
1046
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02001047 ir.continue_block_to_loop_header[current_block->continue_block] = BlockID(current_block->self);
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001048
1049 // Don't add loop headers to continue blocks,
1050 // which would make it impossible branch into the loop header since
1051 // they are treated as continues.
Hans-Kristian Arntzen333980a2019-09-05 12:43:40 +02001052 if (current_block->continue_block != BlockID(current_block->self))
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001053 ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
1054
1055 if (length >= 3)
1056 {
1057 if (ops[2] & LoopControlUnrollMask)
1058 current_block->hint = SPIRBlock::HintUnroll;
1059 else if (ops[2] & LoopControlDontUnrollMask)
1060 current_block->hint = SPIRBlock::HintDontUnroll;
1061 }
1062 break;
1063 }
1064
1065 case OpSpecConstantOp:
1066 {
1067 if (length < 3)
1068 SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
1069
1070 uint32_t result_type = ops[0];
1071 uint32_t id = ops[1];
1072 auto spec_op = static_cast<Op>(ops[2]);
1073
1074 set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
1075 break;
1076 }
1077
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001078 case OpLine:
1079 {
1080 // OpLine might come at global scope, but we don't care about those since they will not be declared in any
1081 // meaningful correct order.
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001082 // Ignore all OpLine directives which live outside a function.
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001083 if (current_block)
1084 current_block->ops.push_back(instruction);
1085
Hans-Kristian Arntzen48a7da42019-05-28 15:51:42 +02001086 // Line directives may arrive before first OpLabel.
1087 // Treat this as the line of the function declaration,
1088 // so warnings for arguments can propagate properly.
1089 if (current_function)
Hans-Kristian Arntzen65af09d2019-05-28 13:41:46 +02001090 {
1091 // Store the first one we find and emit it before creating the function prototype.
1092 if (current_function->entry_line.file_id == 0)
1093 {
1094 current_function->entry_line.file_id = ops[0];
1095 current_function->entry_line.line_literal = ops[1];
1096 }
1097 }
1098 break;
1099 }
1100
Lifeng Pan5ca87792019-07-04 16:03:06 +08001101 case OpNoLine:
1102 {
1103 // OpNoLine might come at global scope.
1104 if (current_block)
1105 current_block->ops.push_back(instruction);
Hans-Kristian Arntzen13378ad2019-07-05 10:25:18 +02001106 break;
Lifeng Pan5ca87792019-07-04 16:03:06 +08001107 }
1108
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001109 // Actual opcodes.
1110 default:
1111 {
1112 if (!current_block)
1113 SPIRV_CROSS_THROW("Currently no block to insert opcode.");
1114
1115 current_block->ops.push_back(instruction);
1116 break;
1117 }
1118 }
1119}
1120
1121bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
1122{
1123 if (a.basetype != b.basetype)
1124 return false;
1125 if (a.width != b.width)
1126 return false;
1127 if (a.vecsize != b.vecsize)
1128 return false;
1129 if (a.columns != b.columns)
1130 return false;
1131 if (a.array.size() != b.array.size())
1132 return false;
1133
1134 size_t array_count = a.array.size();
1135 if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
1136 return false;
1137
1138 if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
1139 {
1140 if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
1141 return false;
1142 }
1143
1144 if (a.member_types.size() != b.member_types.size())
1145 return false;
1146
1147 size_t member_types = a.member_types.size();
1148 for (size_t i = 0; i < member_types; i++)
1149 {
1150 if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
1151 return false;
1152 }
1153
1154 return true;
1155}
1156
1157bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
1158{
1159 auto &type = get<SPIRType>(v.basetype);
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001160
1161 auto *type_meta = ir.find_meta(type.self);
1162
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001163 bool ssbo = v.storage == StorageClassStorageBuffer ||
Hans-Kristian Arntzenb6298782019-01-10 14:04:01 +01001164 (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
Hans-Kristian Arntzen5bcf02f2018-10-05 11:30:57 +02001165 bool image = type.basetype == SPIRType::Image;
1166 bool counter = type.basetype == SPIRType::AtomicCounter;
1167
1168 bool is_restrict;
1169 if (ssbo)
1170 is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
1171 else
1172 is_restrict = ir.has_decoration(v.self, DecorationRestrict);
1173
1174 return !is_restrict && (ssbo || image || counter);
1175}
Hans-Kristian Arntzena489ba72019-04-02 11:19:03 +02001176} // namespace SPIRV_CROSS_NAMESPACE