Debian Codegraph @

thirdparty/spirv-cross/spirv_common.hpp

raw symbols SCIP
1 /*
2 * Copyright 2015-2021 Arm Limited
3 * SPDX-License-Identifier: Apache-2.0 OR MIT
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18 /*
19 * At your option, you may choose to accept this material under either:
20 * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
21 * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
22 */
23
24 #ifndef SPIRV_CROSS_COMMON_HPP
25 #define SPIRV_CROSS_COMMON_HPP
26
27 #ifndef SPV_ENABLE_UTILITY_CODE
28 #define SPV_ENABLE_UTILITY_CODE
29 #endif
30 #include "spirv.hpp"
31
32 #include "spirv_cross_containers.hpp"
33 #include "spirv_cross_error_handling.hpp"
34 #include <functional>
35
36 // A bit crude, but allows projects which embed SPIRV-Cross statically to
37 // effectively hide all the symbols from other projects.
38 // There is a case where we have:
39 // - Project A links against SPIRV-Cross statically.
40 // - Project A links against Project B statically.
41 // - Project B links against SPIRV-Cross statically (might be a different version).
42 // This leads to a conflict with extremely bizarre results.
43 // By overriding the namespace in one of the project builds, we can work around this.
44 // If SPIRV-Cross is embedded in dynamic libraries,
45 // prefer using -fvisibility=hidden on GCC/Clang instead.
46 #ifdef SPIRV_CROSS_NAMESPACE_OVERRIDE
47 #define SPIRV_CROSS_NAMESPACE SPIRV_CROSS_NAMESPACE_OVERRIDE
48 #else
49 #define SPIRV_CROSS_NAMESPACE spirv_cross
50 #endif
51
52 namespace SPIRV_CROSS_NAMESPACE
53 {
54 namespace inner
55 {
56 template <typename T>
57 void join_helper(StringStream<> &stream, T &&t)
58 {
59 stream << std::forward<T>(t);
60 }
61
62 template <typename T, typename... Ts>
63 void join_helper(StringStream<> &stream, T &&t, Ts &&... ts)
64 {
65 stream << std::forward<T>(t);
66 join_helper(stream, std::forward<Ts>(ts)...);
67 }
68 } // namespace inner
69
70 class Bitset
71 {
72 public:
73 Bitset() = default;
74 explicit inline Bitset(uint64_t lower_)
75 : lower(lower_)
76 {
77 }
78
79 inline bool get(uint32_t bit) const
80 {
81 if (bit < 64)
82 return (lower & (1ull << bit)) != 0;
83 else
84 return higher.count(bit) != 0;
85 }
86
87 inline void set(uint32_t bit)
88 {
89 if (bit < 64)
90 lower |= 1ull << bit;
91 else
92 higher.insert(bit);
93 }
94
95 inline void clear(uint32_t bit)
96 {
97 if (bit < 64)
98 lower &= ~(1ull << bit);
99 else
100 higher.erase(bit);
101 }
102
103 inline uint64_t get_lower() const
104 {
105 return lower;
106 }
107
108 inline void reset()
109 {
110 lower = 0;
111 higher.clear();
112 }
113
114 inline void merge_and(const Bitset &other)
115 {
116 lower &= other.lower;
117 std::unordered_set<uint32_t> tmp_set;
118 for (auto &v : higher)
119 if (other.higher.count(v) != 0)
120 tmp_set.insert(v);
121 higher = std::move(tmp_set);
122 }
123
124 inline void merge_or(const Bitset &other)
125 {
126 lower |= other.lower;
127 for (auto &v : other.higher)
128 higher.insert(v);
129 }
130
131 inline bool operator==(const Bitset &other) const
132 {
133 if (lower != other.lower)
134 return false;
135
136 if (higher.size() != other.higher.size())
137 return false;
138
139 for (auto &v : higher)
140 if (other.higher.count(v) == 0)
141 return false;
142
143 return true;
144 }
145
146 inline bool operator!=(const Bitset &other) const
147 {
148 return !(*this == other);
149 }
150
151 template <typename Op>
152 void for_each_bit(const Op &op) const
153 {
154 // TODO: Add ctz-based iteration.
155 for (uint32_t i = 0; i < 64; i++)
156 {
157 if (lower & (1ull << i))
158 op(i);
159 }
160
161 if (higher.empty())
162 return;
163
164 // Need to enforce an order here for reproducible results,
165 // but hitting this path should happen extremely rarely, so having this slow path is fine.
166 SmallVector<uint32_t> bits;
167 bits.reserve(higher.size());
168 for (auto &v : higher)
169 bits.push_back(v);
170 std::sort(std::begin(bits), std::end(bits));
171
172 for (auto &v : bits)
173 op(v);
174 }
175
176 inline bool empty() const
177 {
178 return lower == 0 && higher.empty();
179 }
180
181 private:
182 // The most common bits to set are all lower than 64,
183 // so optimize for this case. Bits spilling outside 64 go into a slower data structure.
184 // In almost all cases, higher data structure will not be used.
185 uint64_t lower = 0;
186 std::unordered_set<uint32_t> higher;
187 };
188
189 // Helper template to avoid lots of nasty string temporary munging.
190 template <typename... Ts>
191 std::string join(Ts &&... ts)
192 {
193 StringStream<> stream;
194 inner::join_helper(stream, std::forward<Ts>(ts)...);
195 return stream.str();
196 }
197
198 inline std::string merge(const SmallVector<std::string> &list, const char *between = ", ")
199 {
200 StringStream<> stream;
201 for (auto &elem : list)
202 {
203 stream << elem;
204 if (&elem != &list.back())
205 stream << between;
206 }
207 return stream.str();
208 }
209
210 // Make sure we don't accidentally call this with float or doubles with SFINAE.
211 // Have to use the radix-aware overload.
212 template <typename T, typename std::enable_if<!std::is_floating_point<T>::value, int>::type = 0>
213 inline std::string convert_to_string(const T &t)
214 {
215 return std::to_string(t);
216 }
217
218 static inline std::string convert_to_string(int32_t value)
219 {
220 // INT_MIN is ... special on some backends. If we use a decimal literal, and negate it, we
221 // could accidentally promote the literal to long first, then negate.
222 // To workaround it, emit int(0x80000000) instead.
223 if (value == (std::numeric_limits<int32_t>::min)())
224 return "int(0x80000000)";
225 else
226 return std::to_string(value);
227 }
228
229 static inline std::string convert_to_string(int64_t value, const std::string &int64_type, bool long_long_literal_suffix)
230 {
231 // INT64_MIN is ... special on some backends.
232 // If we use a decimal literal, and negate it, we might overflow the representable numbers.
233 // To workaround it, emit int(0x80000000) instead.
234 if (value == (std::numeric_limits<int64_t>::min)())
235 return join(int64_type, "(0x8000000000000000u", (long_long_literal_suffix ? "ll" : "l"), ")");
236 else
237 return std::to_string(value) + (long_long_literal_suffix ? "ll" : "l");
238 }
239
240 // Allow implementations to set a convenient standard precision
241 #ifndef SPIRV_CROSS_FLT_FMT
242 #define SPIRV_CROSS_FLT_FMT "%.32g"
243 #endif
244
245 // Disable sprintf and strcat warnings.
246 // We cannot rely on snprintf and family existing because, ..., MSVC.
247 #if defined(__clang__) || defined(__GNUC__)
248 #pragma GCC diagnostic push
249 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
250 #elif defined(_MSC_VER)
251 #pragma warning(push)
252 #pragma warning(disable : 4996)
253 #endif
254
255 static inline void fixup_radix_point(char *str, char radix_point)
256 {
257 // Setting locales is a very risky business in multi-threaded program,
258 // so just fixup locales instead. We only need to care about the radix point.
259 if (radix_point != '.')
260 {
261 while (*str != '\0')
262 {
263 if (*str == radix_point)
264 *str = '.';
265 str++;
266 }
267 }
268 }
269
270 inline std::string convert_to_string(float t, char locale_radix_point)
271 {
272 // std::to_string for floating point values is broken.
273 // Fallback to something more sane.
274 char buf[64];
275 sprintf(buf, SPIRV_CROSS_FLT_FMT, t);
276 fixup_radix_point(buf, locale_radix_point);
277
278 // Ensure that the literal is float.
279 if (!strchr(buf, '.') && !strchr(buf, 'e'))
280 strcat(buf, ".0");
281 return buf;
282 }
283
284 inline std::string convert_to_string(double t, char locale_radix_point)
285 {
286 // std::to_string for floating point values is broken.
287 // Fallback to something more sane.
288 char buf[64];
289 sprintf(buf, SPIRV_CROSS_FLT_FMT, t);
290 fixup_radix_point(buf, locale_radix_point);
291
292 // Ensure that the literal is float.
293 if (!strchr(buf, '.') && !strchr(buf, 'e'))
294 strcat(buf, ".0");
295 return buf;
296 }
297
298 #if defined(__clang__) || defined(__GNUC__)
299 #pragma GCC diagnostic pop
300 #elif defined(_MSC_VER)
301 #pragma warning(pop)
302 #endif
303
304 class FloatFormatter
305 {
306 public:
307 virtual ~FloatFormatter() = default;
308 virtual std::string format_float(float value) = 0;
309 virtual std::string format_double(double value) = 0;
310 };
311
312 template <typename T>
313 struct ValueSaver
314 {
315 explicit ValueSaver(T &current_)
316 : current(current_)
317 , saved(current_)
318 {
319 }
320
321 void release()
322 {
323 current = saved;
324 }
325
326 ~ValueSaver()
327 {
328 release();
329 }
330
331 T &current;
332 T saved;
333 };
334
335 struct Instruction
336 {
337 uint16_t op = 0;
338 uint16_t count = 0;
339 // If offset is 0 (not a valid offset into the instruction stream),
340 // we have an instruction stream which is embedded in the object.
341 uint32_t offset = 0;
342 uint32_t length = 0;
343
344 inline bool is_embedded() const
345 {
346 return offset == 0;
347 }
348 };
349
350 struct EmbeddedInstruction : Instruction
351 {
352 SmallVector<uint32_t> ops;
353 };
354
355 enum Types
356 {
357 TypeNone,
358 TypeType,
359 TypeVariable,
360 TypeConstant,
361 TypeFunction,
362 TypeFunctionPrototype,
363 TypeBlock,
364 TypeExtension,
365 TypeExpression,
366 TypeConstantOp,
367 TypeCombinedImageSampler,
368 TypeAccessChain,
369 TypeUndef,
370 TypeString,
371 TypeCount
372 };
373
374 template <Types type>
375 class TypedID;
376
377 template <>
378 class TypedID<TypeNone>
379 {
380 public:
381 TypedID() = default;
382 TypedID(uint32_t id_)
383 : id(id_)
384 {
385 }
386
387 template <Types U>
388 TypedID(const TypedID<U> &other)
389 {
390 *this = other;
391 }
392
393 template <Types U>
394 TypedID &operator=(const TypedID<U> &other)
395 {
396 id = uint32_t(other);
397 return *this;
398 }
399
400 // Implicit conversion to u32 is desired here.
401 // As long as we block implicit conversion between TypedID<A> and TypedID<B> we're good.
402 operator uint32_t() const
403 {
404 return id;
405 }
406
407 template <Types U>
408 operator TypedID<U>() const
409 {
410 return TypedID<U>(*this);
411 }
412
413 private:
414 uint32_t id = 0;
415 };
416
417 template <Types type>
418 class TypedID
419 {
420 public:
421 TypedID() = default;
422 TypedID(uint32_t id_)
423 : id(id_)
424 {
425 }
426
427 explicit TypedID(const TypedID<TypeNone> &other)
428 : id(uint32_t(other))
429 {
430 }
431
432 operator uint32_t() const
433 {
434 return id;
435 }
436
437 private:
438 uint32_t id = 0;
439 };
440
441 using VariableID = TypedID<TypeVariable>;
442 using TypeID = TypedID<TypeType>;
443 using ConstantID = TypedID<TypeConstant>;
444 using FunctionID = TypedID<TypeFunction>;
445 using BlockID = TypedID<TypeBlock>;
446 using ID = TypedID<TypeNone>;
447
448 // Helper for Variant interface.
449 struct IVariant
450 {
451 virtual ~IVariant() = default;
452 virtual IVariant *clone(ObjectPoolBase *pool) = 0;
453 ID self = 0;
454
455 protected:
456 IVariant() = default;
457 IVariant(const IVariant&) = default;
458 IVariant &operator=(const IVariant&) = default;
459 };
460
461 #define SPIRV_CROSS_DECLARE_CLONE(T) \
462 IVariant *clone(ObjectPoolBase *pool) override \
463 { \
464 return static_cast<ObjectPool<T> *>(pool)->allocate(*this); \
465 }
466
467 struct SPIRUndef : IVariant
468 {
469 enum
470 {
471 type = TypeUndef
472 };
473
474 explicit SPIRUndef(TypeID basetype_)
475 : basetype(basetype_)
476 {
477 }
478 TypeID basetype;
479
480 SPIRV_CROSS_DECLARE_CLONE(SPIRUndef)
481 };
482
483 struct SPIRString : IVariant
484 {
485 enum
486 {
487 type = TypeString
488 };
489
490 explicit SPIRString(std::string str_)
491 : str(std::move(str_))
492 {
493 }
494
495 std::string str;
496
497 SPIRV_CROSS_DECLARE_CLONE(SPIRString)
498 };
499
500 // This type is only used by backends which need to access the combined image and sampler IDs separately after
501 // the OpSampledImage opcode.
502 struct SPIRCombinedImageSampler : IVariant
503 {
504 enum
505 {
506 type = TypeCombinedImageSampler
507 };
508 SPIRCombinedImageSampler(TypeID type_, VariableID image_, VariableID sampler_)
509 : combined_type(type_)
510 , image(image_)
511 , sampler(sampler_)
512 {
513 }
514 TypeID combined_type;
515 VariableID image;
516 VariableID sampler;
517
518 SPIRV_CROSS_DECLARE_CLONE(SPIRCombinedImageSampler)
519 };
520
521 struct SPIRConstantOp : IVariant
522 {
523 enum
524 {
525 type = TypeConstantOp
526 };
527
528 SPIRConstantOp(TypeID result_type, spv::Op op, const uint32_t *args, uint32_t length)
529 : opcode(op)
530 , basetype(result_type)
531 {
532 arguments.reserve(length);
533 for (uint32_t i = 0; i < length; i++)
534 arguments.push_back(args[i]);
535 }
536
537 spv::Op opcode;
538 SmallVector<uint32_t> arguments;
539 TypeID basetype;
540
541 SPIRV_CROSS_DECLARE_CLONE(SPIRConstantOp)
542 };
543
544 struct SPIRType : IVariant
545 {
546 enum
547 {
548 type = TypeType
549 };
550
551 spv::Op op = spv::Op::OpNop;
552 explicit SPIRType(spv::Op op_) : op(op_) {}
553
554 enum BaseType
555 {
556 Unknown,
557 Void,
558 Boolean,
559 SByte,
560 UByte,
561 Short,
562 UShort,
563 Int,
564 UInt,
565 Int64,
566 UInt64,
567 AtomicCounter,
568 Half,
569 Float,
570 Double,
571 Struct,
572 Image,
573 SampledImage,
574 Sampler,
575 AccelerationStructure,
576 RayQuery,
577
578 // Keep internal types at the end.
579 ControlPointArray,
580 Interpolant,
581 Char,
582 // MSL specific type, that is used by 'object'(analog of 'task' from glsl) shader.
583 MeshGridProperties,
584 BFloat16,
585 FloatE4M3,
586 FloatE5M2
587 };
588
589 // Scalar/vector/matrix support.
590 BaseType basetype = Unknown;
591 uint32_t width = 0;
592 uint32_t vecsize = 1;
593 uint32_t columns = 1;
594
595 // Arrays, support array of arrays by having a vector of array sizes.
596 SmallVector<uint32_t> array;
597
598 // Array elements can be either specialization constants or specialization ops.
599 // This array determines how to interpret the array size.
600 // If an element is true, the element is a literal,
601 // otherwise, it's an expression, which must be resolved on demand.
602 // The actual size is not really known until runtime.
603 SmallVector<bool> array_size_literal;
604
605 // Pointers
606 // Keep track of how many pointer layers we have.
607 uint32_t pointer_depth = 0;
608 bool pointer = false;
609 bool forward_pointer = false;
610
611 struct
612 {
613 uint32_t use_id = 0;
614 uint32_t rows_id = 0;
615 uint32_t columns_id = 0;
616 uint32_t scope_id = 0;
617 } cooperative;
618
619 spv::StorageClass storage = spv::StorageClassGeneric;
620
621 SmallVector<TypeID> member_types;
622
623 // If member order has been rewritten to handle certain scenarios with Offset,
624 // allow codegen to rewrite the index.
625 SmallVector<uint32_t> member_type_index_redirection;
626
627 struct ImageType
628 {
629 TypeID type;
630 spv::Dim dim;
631 bool depth;
632 bool arrayed;
633 bool ms;
634 uint32_t sampled;
635 spv::ImageFormat format;
636 spv::AccessQualifier access;
637 } image = {};
638
639 // Structs can be declared multiple times if they are used as part of interface blocks.
640 // We want to detect this so that we only emit the struct definition once.
641 // Since we cannot rely on OpName to be equal, we need to figure out aliases.
642 TypeID type_alias = 0;
643
644 // Denotes the type which this type is based on.
645 // Allows the backend to traverse how a complex type is built up during access chains.
646 TypeID parent_type = 0;
647
648 // Used in backends to avoid emitting members with conflicting names.
649 std::unordered_set<std::string> member_name_cache;
650
651 SPIRV_CROSS_DECLARE_CLONE(SPIRType)
652 };
653
654 struct SPIRExtension : IVariant
655 {
656 enum
657 {
658 type = TypeExtension
659 };
660
661 enum Extension
662 {
663 Unsupported,
664 GLSL,
665 SPV_debug_info,
666 SPV_AMD_shader_ballot,
667 SPV_AMD_shader_explicit_vertex_parameter,
668 SPV_AMD_shader_trinary_minmax,
669 SPV_AMD_gcn_shader,
670 NonSemanticDebugPrintf,
671 NonSemanticShaderDebugInfo,
672 NonSemanticGeneric
673 };
674
675 explicit SPIRExtension(Extension ext_)
676 : ext(ext_)
677 {
678 }
679
680 Extension ext;
681 SPIRV_CROSS_DECLARE_CLONE(SPIRExtension)
682 };
683
684 // SPIREntryPoint is not a variant since its IDs are used to decorate OpFunction,
685 // so in order to avoid conflicts, we can't stick them in the ids array.
686 struct SPIREntryPoint
687 {
688 SPIREntryPoint(FunctionID self_, spv::ExecutionModel execution_model, const std::string &entry_name)
689 : self(self_)
690 , name(entry_name)
691 , orig_name(entry_name)
692 , model(execution_model)
693 {
694 }
695 SPIREntryPoint() = default;
696
697 FunctionID self = 0;
698 std::string name;
699 std::string orig_name;
700 std::unordered_map<uint32_t, uint32_t> fp_fast_math_defaults;
701 SmallVector<VariableID> interface_variables;
702
703 Bitset flags;
704 struct WorkgroupSize
705 {
706 uint32_t x = 0, y = 0, z = 0;
707 uint32_t id_x = 0, id_y = 0, id_z = 0;
708 uint32_t constant = 0; // Workgroup size can be expressed as a constant/spec-constant instead.
709 } workgroup_size;
710 uint32_t invocations = 0;
711 uint32_t output_vertices = 0;
712 uint32_t output_primitives = 0;
713 spv::ExecutionModel model = spv::ExecutionModelMax;
714 bool geometry_passthrough = false;
715 };
716
717 struct SPIRExpression : IVariant
718 {
719 enum
720 {
721 type = TypeExpression
722 };
723
724 // Only created by the backend target to avoid creating tons of temporaries.
725 SPIRExpression(std::string expr, TypeID expression_type_, bool immutable_)
726 : expression(std::move(expr))
727 , expression_type(expression_type_)
728 , immutable(immutable_)
729 {
730 }
731
732 // If non-zero, prepend expression with to_expression(base_expression).
733 // Used in amortizing multiple calls to to_expression()
734 // where in certain cases that would quickly force a temporary when not needed.
735 ID base_expression = 0;
736
737 std::string expression;
738 TypeID expression_type = 0;
739
740 // If this expression is a forwarded load,
741 // allow us to reference the original variable.
742 ID loaded_from = 0;
743
744 // If this expression will never change, we can avoid lots of temporaries
745 // in high level source.
746 // An expression being immutable can be speculative,
747 // it is assumed that this is true almost always.
748 bool immutable = false;
749
750 // Before use, this expression must be transposed.
751 // This is needed for targets which don't support row_major layouts.
752 bool need_transpose = false;
753
754 // Whether or not this is an access chain expression.
755 bool access_chain = false;
756
757 // Whether or not gl_MeshVerticesEXT[].gl_Position (as a whole or .y) is referenced
758 bool access_meshlet_position_y = false;
759
760 // A list of expressions which this expression depends on.
761 SmallVector<ID> expression_dependencies;
762
763 // Similar as expression dependencies, but does not stop the tracking for force-temporary variables.
764 // We need to know the full chain from store back to any SSA variable.
765 SmallVector<ID> invariance_dependencies;
766
767 // By reading this expression, we implicitly read these expressions as well.
768 // Used by access chain Store and Load since we read multiple expressions in this case.
769 SmallVector<ID> implied_read_expressions;
770
771 // The expression was emitted at a certain scope. Lets us track when an expression read means multiple reads.
772 uint32_t emitted_loop_level = 0;
773
774 SPIRV_CROSS_DECLARE_CLONE(SPIRExpression)
775 };
776
777 struct SPIRFunctionPrototype : IVariant
778 {
779 enum
780 {
781 type = TypeFunctionPrototype
782 };
783
784 explicit SPIRFunctionPrototype(TypeID return_type_)
785 : return_type(return_type_)
786 {
787 }
788
789 TypeID return_type;
790 SmallVector<uint32_t> parameter_types;
791
792 SPIRV_CROSS_DECLARE_CLONE(SPIRFunctionPrototype)
793 };
794
795 struct SPIRBlock : IVariant
796 {
797 enum
798 {
799 type = TypeBlock
800 };
801
802 enum Terminator
803 {
804 Unknown,
805 Direct, // Emit next block directly without a particular condition.
806
807 Select, // Block ends with an if/else block.
808 MultiSelect, // Block ends with switch statement.
809
810 Return, // Block ends with return.
811 Unreachable, // Noop
812 Kill, // Discard
813 IgnoreIntersection, // Ray Tracing
814 TerminateRay, // Ray Tracing
815 EmitMeshTasks // Mesh shaders
816 };
817
818 enum Merge
819 {
820 MergeNone,
821 MergeLoop,
822 MergeSelection
823 };
824
825 enum Hints
826 {
827 HintNone,
828 HintUnroll,
829 HintDontUnroll,
830 HintFlatten,
831 HintDontFlatten
832 };
833
834 enum Method
835 {
836 MergeToSelectForLoop,
837 MergeToDirectForLoop,
838 MergeToSelectContinueForLoop
839 };
840
841 enum ContinueBlockType
842 {
843 ContinueNone,
844
845 // Continue block is branchless and has at least one instruction.
846 ForLoop,
847
848 // Noop continue block.
849 WhileLoop,
850
851 // Continue block is conditional.
852 DoWhileLoop,
853
854 // Highly unlikely that anything will use this,
855 // since it is really awkward/impossible to express in GLSL.
856 ComplexLoop
857 };
858
859 enum : uint32_t
860 {
861 NoDominator = 0xffffffffu
862 };
863
864 Terminator terminator = Unknown;
865 Merge merge = MergeNone;
866 Hints hint = HintNone;
867 BlockID next_block = 0;
868 BlockID merge_block = 0;
869 BlockID continue_block = 0;
870
871 ID return_value = 0; // If 0, return nothing (void).
872 ID condition = 0;
873 BlockID true_block = 0;
874 BlockID false_block = 0;
875 BlockID default_block = 0;
876
877 // If terminator is EmitMeshTasksEXT.
878 struct
879 {
880 ID groups[3];
881 ID payload;
882 } mesh = {};
883
884 SmallVector<Instruction> ops;
885
886 struct Phi
887 {
888 ID local_variable; // flush local variable ...
889 BlockID parent; // If we're in from_block and want to branch into this block ...
890 VariableID function_variable; // to this function-global "phi" variable first.
891 };
892
893 // Before entering this block flush out local variables to magical "phi" variables.
894 SmallVector<Phi> phi_variables;
895
896 // Declare these temporaries before beginning the block.
897 // Used for handling complex continue blocks which have side effects.
898 SmallVector<std::pair<TypeID, ID>> declare_temporary;
899
900 // Declare these temporaries, but only conditionally if this block turns out to be
901 // a complex loop header.
902 SmallVector<std::pair<TypeID, ID>> potential_declare_temporary;
903
904 struct Case
905 {
906 uint64_t value;
907 BlockID block;
908 };
909 SmallVector<Case> cases_32bit;
910 SmallVector<Case> cases_64bit;
911
912 // If we have tried to optimize code for this block but failed,
913 // keep track of this.
914 bool disable_block_optimization = false;
915
916 // If the continue block is complex, fallback to "dumb" for loops.
917 bool complex_continue = false;
918
919 // Do we need a ladder variable to defer breaking out of a loop construct after a switch block?
920 bool need_ladder_break = false;
921
922 // If marked, we have explicitly handled Phi from this block, so skip any flushes related to that on a branch.
923 // Used to handle an edge case with switch and case-label fallthrough where fall-through writes to Phi.
924 BlockID ignore_phi_from_block = 0;
925
926 // The dominating block which this block might be within.
927 // Used in continue; blocks to determine if we really need to write continue.
928 BlockID loop_dominator = 0;
929
930 // All access to these variables are dominated by this block,
931 // so before branching anywhere we need to make sure that we declare these variables.
932 SmallVector<VariableID> dominated_variables;
933
934 // These are variables which should be declared in a for loop header, if we
935 // fail to use a classic for-loop,
936 // we remove these variables, and fall back to regular variables outside the loop.
937 SmallVector<VariableID> loop_variables;
938
939 // Some expressions are control-flow dependent, i.e. any instruction which relies on derivatives or
940 // sub-group-like operations.
941 // Make sure that we only use these expressions in the original block.
942 SmallVector<ID> invalidate_expressions;
943
944 SPIRV_CROSS_DECLARE_CLONE(SPIRBlock)
945 };
946
947 struct SPIRFunction : IVariant
948 {
949 enum
950 {
951 type = TypeFunction
952 };
953
954 SPIRFunction(TypeID return_type_, TypeID function_type_)
955 : return_type(return_type_)
956 , function_type(function_type_)
957 {
958 }
959
960 struct Parameter
961 {
962 TypeID type;
963 ID id;
964 uint32_t read_count;
965 uint32_t write_count;
966
967 // Set to true if this parameter aliases a global variable,
968 // used mostly in Metal where global variables
969 // have to be passed down to functions as regular arguments.
970 // However, for this kind of variable, we should not care about
971 // read and write counts as access to the function arguments
972 // is not local to the function in question.
973 bool alias_global_variable;
974 };
975
976 // When calling a function, and we're remapping separate image samplers,
977 // resolve these arguments into combined image samplers and pass them
978 // as additional arguments in this order.
979 // It gets more complicated as functions can pull in their own globals
980 // and combine them with parameters,
981 // so we need to distinguish if something is local parameter index
982 // or a global ID.
983 struct CombinedImageSamplerParameter
984 {
985 VariableID id;
986 VariableID image_id;
987 VariableID sampler_id;
988 bool global_image;
989 bool global_sampler;
990 bool depth;
991 };
992
993 TypeID return_type;
994 TypeID function_type;
995 SmallVector<Parameter> arguments;
996
997 // Can be used by backends to add magic arguments.
998 // Currently used by combined image/sampler implementation.
999
1000 SmallVector<Parameter> shadow_arguments;
1001 SmallVector<VariableID> local_variables;
1002 BlockID entry_block = 0;
1003 SmallVector<BlockID> blocks;
1004 SmallVector<CombinedImageSamplerParameter> combined_parameters;
1005
1006 struct EntryLine
1007 {
1008 uint32_t file_id = 0;
1009 uint32_t line_literal = 0;
1010 };
1011 EntryLine entry_line;
1012
1013 void add_local_variable(VariableID id)
1014 {
1015 local_variables.push_back(id);
1016 }
1017
1018 void add_parameter(TypeID parameter_type, ID id, bool alias_global_variable = false)
1019 {
1020 // Arguments are read-only until proven otherwise.
1021 arguments.push_back({ parameter_type, id, 0u, 0u, alias_global_variable });
1022 }
1023
1024 // Hooks to be run when the function returns.
1025 // Mostly used for lowering internal data structures onto flattened structures.
1026 // Need to defer this, because they might rely on things which change during compilation.
1027 // Intentionally not a small vector, this one is rare, and std::function can be large.
1028 Vector<std::function<void()>> fixup_hooks_out;
1029
1030 // Hooks to be run when the function begins.
1031 // Mostly used for populating internal data structures from flattened structures.
1032 // Need to defer this, because they might rely on things which change during compilation.
1033 // Intentionally not a small vector, this one is rare, and std::function can be large.
1034 Vector<std::function<void()>> fixup_hooks_in;
1035
1036 // On function entry, make sure to copy a constant array into thread addr space to work around
1037 // the case where we are passing a constant array by value to a function on backends which do not
1038 // consider arrays value types.
1039 SmallVector<ID> constant_arrays_needed_on_stack;
1040
1041 // Does this function (or any function called by it), emit geometry?
1042 bool emits_geometry = false;
1043
1044 bool active = false;
1045 bool flush_undeclared = true;
1046 bool do_combined_parameters = true;
1047
1048 SPIRV_CROSS_DECLARE_CLONE(SPIRFunction)
1049 };
1050
1051 struct SPIRAccessChain : IVariant
1052 {
1053 enum
1054 {
1055 type = TypeAccessChain
1056 };
1057
1058 SPIRAccessChain(TypeID basetype_, spv::StorageClass storage_, std::string base_, std::string dynamic_index_,
1059 int32_t static_index_)
1060 : basetype(basetype_)
1061 , storage(storage_)
1062 , base(std::move(base_))
1063 , dynamic_index(std::move(dynamic_index_))
1064 , static_index(static_index_)
1065 {
1066 }
1067
1068 // The access chain represents an offset into a buffer.
1069 // Some backends need more complicated handling of access chains to be able to use buffers, like HLSL
1070 // which has no usable buffer type ala GLSL SSBOs.
1071 // StructuredBuffer is too limited, so our only option is to deal with ByteAddressBuffer which works with raw addresses.
1072
1073 TypeID basetype;
1074 spv::StorageClass storage;
1075 std::string base;
1076 std::string dynamic_index;
1077 int32_t static_index;
1078
1079 VariableID loaded_from = 0;
1080 uint32_t matrix_stride = 0;
1081 uint32_t array_stride = 0;
1082 bool row_major_matrix = false;
1083 bool immutable = false;
1084
1085 // By reading this expression, we implicitly read these expressions as well.
1086 // Used by access chain Store and Load since we read multiple expressions in this case.
1087 SmallVector<ID> implied_read_expressions;
1088
1089 SPIRV_CROSS_DECLARE_CLONE(SPIRAccessChain)
1090 };
1091
1092 struct SPIRVariable : IVariant
1093 {
1094 enum
1095 {
1096 type = TypeVariable
1097 };
1098
1099 SPIRVariable() = default;
1100 SPIRVariable(TypeID basetype_, spv::StorageClass storage_, ID initializer_ = 0, VariableID basevariable_ = 0)
1101 : basetype(basetype_)
1102 , storage(storage_)
1103 , initializer(initializer_)
1104 , basevariable(basevariable_)
1105 {
1106 }
1107
1108 TypeID basetype = 0;
1109 spv::StorageClass storage = spv::StorageClassGeneric;
1110 uint32_t decoration = 0;
1111 ID initializer = 0;
1112 VariableID basevariable = 0;
1113
1114 SmallVector<uint32_t> dereference_chain;
1115 bool compat_builtin = false;
1116
1117 // If a variable is shadowed, we only statically assign to it
1118 // and never actually emit a statement for it.
1119 // When we read the variable as an expression, just forward
1120 // shadowed_id as the expression.
1121 bool statically_assigned = false;
1122 ID static_expression = 0;
1123
1124 // Temporaries which can remain forwarded as long as this variable is not modified.
1125 SmallVector<ID> dependees;
1126
1127 bool deferred_declaration = false;
1128 bool phi_variable = false;
1129
1130 // Used to deal with Phi variable flushes. See flush_phi().
1131 bool allocate_temporary_copy = false;
1132
1133 bool remapped_variable = false;
1134 uint32_t remapped_components = 0;
1135
1136 // The block which dominates all access to this variable.
1137 BlockID dominator = 0;
1138 // If true, this variable is a loop variable, when accessing the variable
1139 // outside a loop,
1140 // we should statically forward it.
1141 bool loop_variable = false;
1142 // Set to true while we're inside the for loop.
1143 bool loop_variable_enable = false;
1144
1145 // Used to find global LUTs
1146 bool is_written_to = false;
1147
1148 SPIRFunction::Parameter *parameter = nullptr;
1149
1150 SPIRV_CROSS_DECLARE_CLONE(SPIRVariable)
1151 };
1152
1153 struct SPIRConstant : IVariant
1154 {
1155 enum
1156 {
1157 type = TypeConstant
1158 };
1159
1160 union Constant
1161 {
1162 uint32_t u32;
1163 int32_t i32;
1164 float f32;
1165
1166 uint64_t u64;
1167 int64_t i64;
1168 double f64;
1169 };
1170
1171 struct ConstantVector
1172 {
1173 Constant r[4];
1174 // If != 0, this element is a specialization constant, and we should keep track of it as such.
1175 ID id[4];
1176 uint32_t vecsize = 1;
1177
1178 ConstantVector()
1179 {
1180 memset(r, 0, sizeof(r));
1181 }
1182 };
1183
1184 struct ConstantMatrix
1185 {
1186 ConstantVector c[4];
1187 // If != 0, this column is a specialization constant, and we should keep track of it as such.
1188 ID id[4];
1189 uint32_t columns = 1;
1190 };
1191
1192 static inline float f16_to_f32(uint16_t u16_value)
1193 {
1194 // Based on the GLM implementation.
1195 int s = (u16_value >> 15) & 0x1;
1196 int e = (u16_value >> 10) & 0x1f;
1197 int m = (u16_value >> 0) & 0x3ff;
1198
1199 union
1200 {
1201 float f32;
1202 uint32_t u32;
1203 } u;
1204
1205 if (e == 0)
1206 {
1207 if (m == 0)
1208 {
1209 u.u32 = uint32_t(s) << 31;
1210 return u.f32;
1211 }
1212 else
1213 {
1214 while ((m & 0x400) == 0)
1215 {
1216 m <<= 1;
1217 e--;
1218 }
1219
1220 e++;
1221 m &= ~0x400;
1222 }
1223 }
1224 else if (e == 31)
1225 {
1226 if (m == 0)
1227 {
1228 u.u32 = (uint32_t(s) << 31) | 0x7f800000u;
1229 return u.f32;
1230 }
1231 else
1232 {
1233 u.u32 = (uint32_t(s) << 31) | 0x7f800000u | (m << 13);
1234 return u.f32;
1235 }
1236 }
1237
1238 e += 127 - 15;
1239 m <<= 13;
1240 u.u32 = (uint32_t(s) << 31) | (e << 23) | m;
1241 return u.f32;
1242 }
1243
1244 static inline float fe4m3_to_f32(uint8_t v)
1245 {
1246 if ((v & 0x7f) == 0x7f)
1247 {
1248 union
1249 {
1250 float f32;
1251 uint32_t u32;
1252 } u;
1253
1254 u.u32 = (v & 0x80) ? 0xffffffffu : 0x7fffffffu;
1255 return u.f32;
1256 }
1257 else
1258 {
1259 // Reuse the FP16 to FP32 code. Cute bit-hackery.
1260 return f16_to_f32((int16_t(int8_t(v)) << 7) & (0xffff ^ 0x4000)) * 256.0f;
1261 }
1262 }
1263
1264 inline uint32_t specialization_constant_id(uint32_t col, uint32_t row) const
1265 {
1266 return m.c[col].id[row];
1267 }
1268
1269 inline uint32_t specialization_constant_id(uint32_t col) const
1270 {
1271 return m.id[col];
1272 }
1273
1274 inline uint32_t scalar(uint32_t col = 0, uint32_t row = 0) const
1275 {
1276 return m.c[col].r[row].u32;
1277 }
1278
1279 inline int16_t scalar_i16(uint32_t col = 0, uint32_t row = 0) const
1280 {
1281 return int16_t(m.c[col].r[row].u32 & 0xffffu);
1282 }
1283
1284 inline uint16_t scalar_u16(uint32_t col = 0, uint32_t row = 0) const
1285 {
1286 return uint16_t(m.c[col].r[row].u32 & 0xffffu);
1287 }
1288
1289 inline int8_t scalar_i8(uint32_t col = 0, uint32_t row = 0) const
1290 {
1291 return int8_t(m.c[col].r[row].u32 & 0xffu);
1292 }
1293
1294 inline uint8_t scalar_u8(uint32_t col = 0, uint32_t row = 0) const
1295 {
1296 return uint8_t(m.c[col].r[row].u32 & 0xffu);
1297 }
1298
1299 inline float scalar_f16(uint32_t col = 0, uint32_t row = 0) const
1300 {
1301 return f16_to_f32(scalar_u16(col, row));
1302 }
1303
1304 inline float scalar_bf16(uint32_t col = 0, uint32_t row = 0) const
1305 {
1306 uint32_t v = scalar_u16(col, row) << 16;
1307 float fp32;
1308 memcpy(&fp32, &v, sizeof(float));
1309 return fp32;
1310 }
1311
1312 inline float scalar_floate4m3(uint32_t col = 0, uint32_t row = 0) const
1313 {
1314 return fe4m3_to_f32(scalar_u8(col, row));
1315 }
1316
1317 inline float scalar_bf8(uint32_t col = 0, uint32_t row = 0) const
1318 {
1319 return f16_to_f32(scalar_u8(col, row) << 8);
1320 }
1321
1322 inline float scalar_f32(uint32_t col = 0, uint32_t row = 0) const
1323 {
1324 return m.c[col].r[row].f32;
1325 }
1326
1327 inline int32_t scalar_i32(uint32_t col = 0, uint32_t row = 0) const
1328 {
1329 return m.c[col].r[row].i32;
1330 }
1331
1332 inline double scalar_f64(uint32_t col = 0, uint32_t row = 0) const
1333 {
1334 return m.c[col].r[row].f64;
1335 }
1336
1337 inline int64_t scalar_i64(uint32_t col = 0, uint32_t row = 0) const
1338 {
1339 return m.c[col].r[row].i64;
1340 }
1341
1342 inline uint64_t scalar_u64(uint32_t col = 0, uint32_t row = 0) const
1343 {
1344 return m.c[col].r[row].u64;
1345 }
1346
1347 inline const ConstantVector &vector() const
1348 {
1349 return m.c[0];
1350 }
1351
1352 inline uint32_t vector_size() const
1353 {
1354 return m.c[0].vecsize;
1355 }
1356
1357 inline uint32_t columns() const
1358 {
1359 return m.columns;
1360 }
1361
1362 inline void make_null(const SPIRType &constant_type_)
1363 {
1364 m = {};
1365 m.columns = constant_type_.columns;
1366 for (auto &c : m.c)
1367 c.vecsize = constant_type_.vecsize;
1368 }
1369
1370 inline bool constant_is_null() const
1371 {
1372 if (specialization)
1373 return false;
1374 if (!subconstants.empty())
1375 return false;
1376
1377 for (uint32_t col = 0; col < columns(); col++)
1378 for (uint32_t row = 0; row < vector_size(); row++)
1379 if (scalar_u64(col, row) != 0)
1380 return false;
1381
1382 return true;
1383 }
1384
1385 explicit SPIRConstant(uint32_t constant_type_)
1386 : constant_type(constant_type_)
1387 {
1388 }
1389
1390 SPIRConstant() = default;
1391
1392 SPIRConstant(TypeID constant_type_, const uint32_t *elements, uint32_t num_elements, bool specialized, bool replicated_ = false)
1393 : constant_type(constant_type_)
1394 , specialization(specialized)
1395 , replicated(replicated_)
1396 {
1397 subconstants.reserve(num_elements);
1398 for (uint32_t i = 0; i < num_elements; i++)
1399 subconstants.push_back(elements[i]);
1400 specialization = specialized;
1401 }
1402
1403 // Construct scalar (32-bit).
1404 SPIRConstant(TypeID constant_type_, uint32_t v0, bool specialized)
1405 : constant_type(constant_type_)
1406 , specialization(specialized)
1407 {
1408 m.c[0].r[0].u32 = v0;
1409 m.c[0].vecsize = 1;
1410 m.columns = 1;
1411 }
1412
1413 // Construct scalar (64-bit).
1414 SPIRConstant(TypeID constant_type_, uint64_t v0, bool specialized)
1415 : constant_type(constant_type_)
1416 , specialization(specialized)
1417 {
1418 m.c[0].r[0].u64 = v0;
1419 m.c[0].vecsize = 1;
1420 m.columns = 1;
1421 }
1422
1423 // Construct vectors and matrices.
1424 SPIRConstant(TypeID constant_type_, const SPIRConstant *const *vector_elements, uint32_t num_elements,
1425 bool specialized)
1426 : constant_type(constant_type_)
1427 , specialization(specialized)
1428 {
1429 bool matrix = vector_elements[0]->m.c[0].vecsize > 1;
1430
1431 if (matrix)
1432 {
1433 m.columns = num_elements;
1434
1435 for (uint32_t i = 0; i < num_elements; i++)
1436 {
1437 m.c[i] = vector_elements[i]->m.c[0];
1438 if (vector_elements[i]->specialization)
1439 m.id[i] = vector_elements[i]->self;
1440 }
1441 }
1442 else
1443 {
1444 m.c[0].vecsize = num_elements;
1445 m.columns = 1;
1446
1447 for (uint32_t i = 0; i < num_elements; i++)
1448 {
1449 m.c[0].r[i] = vector_elements[i]->m.c[0].r[0];
1450 if (vector_elements[i]->specialization)
1451 m.c[0].id[i] = vector_elements[i]->self;
1452 }
1453 }
1454 }
1455
1456 TypeID constant_type = 0;
1457 ConstantMatrix m;
1458
1459 // If this constant is a specialization constant (i.e. created with OpSpecConstant*).
1460 bool specialization = false;
1461 // If this constant is used as an array length which creates specialization restrictions on some backends.
1462 bool is_used_as_array_length = false;
1463
1464 // If true, this is a LUT, and should always be declared in the outer scope.
1465 bool is_used_as_lut = false;
1466
1467 // If this is a null constant of array type with specialized length.
1468 // May require special handling in initializer
1469 bool is_null_array_specialized_length = false;
1470
1471 // For composites which are constant arrays, etc.
1472 SmallVector<ConstantID> subconstants;
1473
1474 // Whether the subconstants are intended to be replicated (e.g. OpConstantCompositeReplicateEXT)
1475 bool replicated = false;
1476
1477 // Non-Vulkan GLSL, HLSL and sometimes MSL emits defines for each specialization constant,
1478 // and uses them to initialize the constant. This allows the user
1479 // to still be able to specialize the value by supplying corresponding
1480 // preprocessor directives before compiling the shader.
1481 std::string specialization_constant_macro_name;
1482
1483 SPIRV_CROSS_DECLARE_CLONE(SPIRConstant)
1484 };
1485
1486 // Variants have a very specific allocation scheme.
1487 struct ObjectPoolGroup
1488 {
1489 std::unique_ptr<ObjectPoolBase> pools[TypeCount];
1490 };
1491
1492 class Variant
1493 {
1494 public:
1495 explicit Variant(ObjectPoolGroup *group_)
1496 : group(group_)
1497 {
1498 }
1499
1500 ~Variant()
1501 {
1502 if (holder)
1503 group->pools[type]->deallocate_opaque(holder);
1504 }
1505
1506 // Marking custom move constructor as noexcept is important.
1507 Variant(Variant &&other) SPIRV_CROSS_NOEXCEPT
1508 {
1509 *this = std::move(other);
1510 }
1511
1512 // We cannot copy from other variant without our own pool group.
1513 // Have to explicitly copy.
1514 Variant(const Variant &variant) = delete;
1515
1516 // Marking custom move constructor as noexcept is important.
1517 Variant &operator=(Variant &&other) SPIRV_CROSS_NOEXCEPT
1518 {
1519 if (this != &other)
1520 {
1521 if (holder)
1522 group->pools[type]->deallocate_opaque(holder);
1523 holder = other.holder;
1524 group = other.group;
1525 type = other.type;
1526 allow_type_rewrite = other.allow_type_rewrite;
1527
1528 other.holder = nullptr;
1529 other.type = TypeNone;
1530 }
1531 return *this;
1532 }
1533
1534 // This copy/clone should only be called in the Compiler constructor.
1535 // If this is called inside ::compile(), we invalidate any references we took higher in the stack.
1536 // This should never happen.
1537 Variant &operator=(const Variant &other)
1538 {
1539 //#define SPIRV_CROSS_COPY_CONSTRUCTOR_SANITIZE
1540 #ifdef SPIRV_CROSS_COPY_CONSTRUCTOR_SANITIZE
1541 abort();
1542 #endif
1543 if (this != &other)
1544 {
1545 if (holder)
1546 group->pools[type]->deallocate_opaque(holder);
1547
1548 if (other.holder)
1549 holder = other.holder->clone(group->pools[other.type].get());
1550 else
1551 holder = nullptr;
1552
1553 type = other.type;
1554 allow_type_rewrite = other.allow_type_rewrite;
1555 }
1556 return *this;
1557 }
1558
1559 void set(IVariant *val, Types new_type)
1560 {
1561 if (holder)
1562 group->pools[type]->deallocate_opaque(holder);
1563 holder = nullptr;
1564
1565 if (!allow_type_rewrite && type != TypeNone && type != new_type)
1566 {
1567 if (val)
1568 group->pools[new_type]->deallocate_opaque(val);
1569 SPIRV_CROSS_THROW("Overwriting a variant with new type.");
1570 }
1571
1572 holder = val;
1573 type = new_type;
1574 allow_type_rewrite = false;
1575 }
1576
1577 template <typename T, typename... Ts>
1578 T *allocate_and_set(Types new_type, Ts &&... ts)
1579 {
1580 T *val = static_cast<ObjectPool<T> &>(*group->pools[new_type]).allocate(std::forward<Ts>(ts)...);
1581 set(val, new_type);
1582 return val;
1583 }
1584
1585 template <typename T>
1586 T &get()
1587 {
1588 if (!holder)
1589 SPIRV_CROSS_THROW("nullptr");
1590 if (static_cast<Types>(T::type) != type)
1591 SPIRV_CROSS_THROW("Bad cast");
1592 return *static_cast<T *>(holder);
1593 }
1594
1595 template <typename T>
1596 const T &get() const
1597 {
1598 if (!holder)
1599 SPIRV_CROSS_THROW("nullptr");
1600 if (static_cast<Types>(T::type) != type)
1601 SPIRV_CROSS_THROW("Bad cast");
1602 return *static_cast<const T *>(holder);
1603 }
1604
1605 Types get_type() const
1606 {
1607 return type;
1608 }
1609
1610 ID get_id() const
1611 {
1612 return holder ? holder->self : ID(0);
1613 }
1614
1615 bool empty() const
1616 {
1617 return !holder;
1618 }
1619
1620 void reset()
1621 {
1622 if (holder)
1623 group->pools[type]->deallocate_opaque(holder);
1624 holder = nullptr;
1625 type = TypeNone;
1626 }
1627
1628 void set_allow_type_rewrite()
1629 {
1630 allow_type_rewrite = true;
1631 }
1632
1633 private:
1634 ObjectPoolGroup *group = nullptr;
1635 IVariant *holder = nullptr;
1636 Types type = TypeNone;
1637 bool allow_type_rewrite = false;
1638 };
1639
1640 template <typename T>
1641 T &variant_get(Variant &var)
1642 {
1643 return var.get<T>();
1644 }
1645
1646 template <typename T>
1647 const T &variant_get(const Variant &var)
1648 {
1649 return var.get<T>();
1650 }
1651
1652 template <typename T, typename... P>
1653 T &variant_set(Variant &var, P &&... args)
1654 {
1655 auto *ptr = var.allocate_and_set<T>(static_cast<Types>(T::type), std::forward<P>(args)...);
1656 return *ptr;
1657 }
1658
1659 struct AccessChainMeta
1660 {
1661 uint32_t storage_physical_type = 0;
1662 bool need_transpose = false;
1663 bool storage_is_packed = false;
1664 bool storage_is_invariant = false;
1665 bool flattened_struct = false;
1666 bool relaxed_precision = false;
1667 bool access_meshlet_position_y = false;
1668 bool chain_is_builtin = false;
1669 spv::BuiltIn builtin = {};
1670 };
1671
1672 enum ExtendedDecorations
1673 {
1674 // Marks if a buffer block is re-packed, i.e. member declaration might be subject to PhysicalTypeID remapping and padding.
1675 SPIRVCrossDecorationBufferBlockRepacked = 0,
1676
1677 // A type in a buffer block might be declared with a different physical type than the logical type.
1678 // If this is not set, PhysicalTypeID == the SPIR-V type as declared.
1679 SPIRVCrossDecorationPhysicalTypeID,
1680
1681 // Marks if the physical type is to be declared with tight packing rules, i.e. packed_floatN on MSL and friends.
1682 // If this is set, PhysicalTypeID might also be set. It can be set to same as logical type if all we're doing
1683 // is converting float3 to packed_float3 for example.
1684 // If this is marked on a struct, it means the struct itself must use only Packed types for all its members.
1685 SPIRVCrossDecorationPhysicalTypePacked,
1686
1687 // The padding in bytes before declaring this struct member.
1688 // If used on a struct type, marks the target size of a struct.
1689 SPIRVCrossDecorationPaddingTarget,
1690
1691 SPIRVCrossDecorationInterfaceMemberIndex,
1692 SPIRVCrossDecorationInterfaceOrigID,
1693 SPIRVCrossDecorationResourceIndexPrimary,
1694 // Used for decorations like resource indices for samplers when part of combined image samplers.
1695 // A variable might need to hold two resource indices in this case.
1696 SPIRVCrossDecorationResourceIndexSecondary,
1697 // Used for resource indices for multiplanar images when part of combined image samplers.
1698 SPIRVCrossDecorationResourceIndexTertiary,
1699 SPIRVCrossDecorationResourceIndexQuaternary,
1700
1701 // Marks a buffer block for using explicit offsets (GLSL/HLSL).
1702 SPIRVCrossDecorationExplicitOffset,
1703
1704 // Apply to a variable in the Input storage class; marks it as holding the base group passed to vkCmdDispatchBase(),
1705 // or the base vertex and instance indices passed to vkCmdDrawIndexed().
1706 // In MSL, this is used to adjust the WorkgroupId and GlobalInvocationId variables in compute shaders,
1707 // and to hold the BaseVertex and BaseInstance variables in vertex shaders.
1708 SPIRVCrossDecorationBuiltInDispatchBase,
1709
1710 // Apply to a variable that is a function parameter; marks it as being a "dynamic"
1711 // combined image-sampler. In MSL, this is used when a function parameter might hold
1712 // either a regular combined image-sampler or one that has an attached sampler
1713 // Y'CbCr conversion.
1714 SPIRVCrossDecorationDynamicImageSampler,
1715
1716 // Apply to a variable in the Input storage class; marks it as holding the size of the stage
1717 // input grid.
1718 // In MSL, this is used to hold the vertex and instance counts in a tessellation pipeline
1719 // vertex shader.
1720 SPIRVCrossDecorationBuiltInStageInputSize,
1721
1722 // Apply to any access chain of a tessellation I/O variable; stores the type of the sub-object
1723 // that was chained to, as recorded in the input variable itself. This is used in case the pointer
1724 // is itself used as the base of an access chain, to calculate the original type of the sub-object
1725 // chained to, in case a swizzle needs to be applied. This should not happen normally with valid
1726 // SPIR-V, but the MSL backend can change the type of input variables, necessitating the
1727 // addition of swizzles to keep the generated code compiling.
1728 SPIRVCrossDecorationTessIOOriginalInputTypeID,
1729
1730 // Apply to any access chain of an interface variable used with pull-model interpolation, where the variable is a
1731 // vector but the resulting pointer is a scalar; stores the component index that is to be accessed by the chain.
1732 // This is used when emitting calls to interpolation functions on the chain in MSL: in this case, the component
1733 // must be applied to the result, since pull-model interpolants in MSL cannot be swizzled directly, but the
1734 // results of interpolation can.
1735 SPIRVCrossDecorationInterpolantComponentExpr,
1736
1737 // Apply to any struct type that is used in the Workgroup storage class.
1738 // This causes matrices in MSL prior to Metal 3.0 to be emitted using a special
1739 // class that is convertible to the standard matrix type, to work around the
1740 // lack of constructors in the 'threadgroup' address space.
1741 SPIRVCrossDecorationWorkgroupStruct,
1742
1743 SPIRVCrossDecorationOverlappingBinding,
1744
1745 SPIRVCrossDecorationCount
1746 };
1747
1748 struct Meta
1749 {
1750 struct Decoration
1751 {
1752 std::string alias;
1753 std::string qualified_alias;
1754 std::string hlsl_semantic;
1755 std::string user_type;
1756 Bitset decoration_flags;
1757 spv::BuiltIn builtin_type = spv::BuiltInMax;
1758 uint32_t location = 0;
1759 uint32_t component = 0;
1760 uint32_t set = 0;
1761 uint32_t binding = 0;
1762 uint32_t offset = 0;
1763 uint32_t xfb_buffer = 0;
1764 uint32_t xfb_stride = 0;
1765 uint32_t stream = 0;
1766 uint32_t array_stride = 0;
1767 uint32_t matrix_stride = 0;
1768 uint32_t input_attachment = 0;
1769 uint32_t spec_id = 0;
1770 uint32_t index = 0;
1771 spv::FPRoundingMode fp_rounding_mode = spv::FPRoundingModeMax;
1772 spv::FPFastMathModeMask fp_fast_math_mode = spv::FPFastMathModeMaskNone;
1773 bool builtin = false;
1774 bool qualified_alias_explicit_override = false;
1775
1776 struct Extended
1777 {
1778 Extended()
1779 {
1780 // MSVC 2013 workaround to init like this.
1781 for (auto &v : values)
1782 v = 0;
1783 }
1784
1785 Bitset flags;
1786 uint32_t values[SPIRVCrossDecorationCount];
1787 } extended;
1788 };
1789
1790 Decoration decoration;
1791
1792 // Intentionally not a SmallVector. Decoration is large and somewhat rare.
1793 Vector<Decoration> members;
1794
1795 std::unordered_map<uint32_t, uint32_t> decoration_word_offset;
1796
1797 // For SPV_GOOGLE_hlsl_functionality1.
1798 bool hlsl_is_magic_counter_buffer = false;
1799 // ID for the sibling counter buffer.
1800 uint32_t hlsl_magic_counter_buffer = 0;
1801 };
1802
1803 // A user callback that remaps the type of any variable.
1804 // var_name is the declared name of the variable.
1805 // name_of_type is the textual name of the type which will be used in the code unless written to by the callback.
1806 using VariableTypeRemapCallback =
1807 std::function<void(const SPIRType &type, const std::string &var_name, std::string &name_of_type)>;
1808
1809 class Hasher
1810 {
1811 public:
1812 inline void u32(uint32_t value)
1813 {
1814 h = (h * 0x100000001b3ull) ^ value;
1815 }
1816
1817 inline uint64_t get() const
1818 {
1819 return h;
1820 }
1821
1822 private:
1823 uint64_t h = 0xcbf29ce484222325ull;
1824 };
1825
1826 static inline bool type_is_floating_point(const SPIRType &type)
1827 {
1828 return type.basetype == SPIRType::Half || type.basetype == SPIRType::Float || type.basetype == SPIRType::Double;
1829 }
1830
1831 static inline bool type_is_integral(const SPIRType &type)
1832 {
1833 return type.basetype == SPIRType::SByte || type.basetype == SPIRType::UByte || type.basetype == SPIRType::Short ||
1834 type.basetype == SPIRType::UShort || type.basetype == SPIRType::Int || type.basetype == SPIRType::UInt ||
1835 type.basetype == SPIRType::Int64 || type.basetype == SPIRType::UInt64;
1836 }
1837
1838 static inline SPIRType::BaseType to_signed_basetype(uint32_t width)
1839 {
1840 switch (width)
1841 {
1842 case 8:
1843 return SPIRType::SByte;
1844 case 16:
1845 return SPIRType::Short;
1846 case 32:
1847 return SPIRType::Int;
1848 case 64:
1849 return SPIRType::Int64;
1850 default:
1851 SPIRV_CROSS_THROW("Invalid bit width.");
1852 }
1853 }
1854
1855 static inline SPIRType::BaseType to_unsigned_basetype(uint32_t width)
1856 {
1857 switch (width)
1858 {
1859 case 8:
1860 return SPIRType::UByte;
1861 case 16:
1862 return SPIRType::UShort;
1863 case 32:
1864 return SPIRType::UInt;
1865 case 64:
1866 return SPIRType::UInt64;
1867 default:
1868 SPIRV_CROSS_THROW("Invalid bit width.");
1869 }
1870 }
1871
1872 // Returns true if an arithmetic operation does not change behavior depending on signedness.
1873 static inline bool opcode_is_sign_invariant(spv::Op opcode)
1874 {
1875 switch (opcode)
1876 {
1877 case spv::OpIEqual:
1878 case spv::OpINotEqual:
1879 case spv::OpISub:
1880 case spv::OpIAdd:
1881 case spv::OpIMul:
1882 case spv::OpShiftLeftLogical:
1883 case spv::OpBitwiseOr:
1884 case spv::OpBitwiseXor:
1885 case spv::OpBitwiseAnd:
1886 return true;
1887
1888 default:
1889 return false;
1890 }
1891 }
1892
1893 static inline bool opcode_can_promote_integer_implicitly(spv::Op opcode)
1894 {
1895 switch (opcode)
1896 {
1897 case spv::OpSNegate:
1898 case spv::OpNot:
1899 case spv::OpBitwiseAnd:
1900 case spv::OpBitwiseOr:
1901 case spv::OpBitwiseXor:
1902 case spv::OpShiftLeftLogical:
1903 case spv::OpShiftRightLogical:
1904 case spv::OpShiftRightArithmetic:
1905 case spv::OpIAdd:
1906 case spv::OpISub:
1907 case spv::OpIMul:
1908 case spv::OpSDiv:
1909 case spv::OpUDiv:
1910 case spv::OpSRem:
1911 case spv::OpUMod:
1912 case spv::OpSMod:
1913 return true;
1914
1915 default:
1916 return false;
1917 }
1918 }
1919
1920 struct SetBindingPair
1921 {
1922 uint32_t desc_set;
1923 uint32_t binding;
1924
1925 inline bool operator==(const SetBindingPair &other) const
1926 {
1927 return desc_set == other.desc_set && binding == other.binding;
1928 }
1929
1930 inline bool operator<(const SetBindingPair &other) const
1931 {
1932 return desc_set < other.desc_set || (desc_set == other.desc_set && binding < other.binding);
1933 }
1934 };
1935
1936 struct LocationComponentPair
1937 {
1938 uint32_t location;
1939 uint32_t component;
1940
1941 inline bool operator==(const LocationComponentPair &other) const
1942 {
1943 return location == other.location && component == other.component;
1944 }
1945
1946 inline bool operator<(const LocationComponentPair &other) const
1947 {
1948 return location < other.location || (location == other.location && component < other.component);
1949 }
1950 };
1951
1952 struct StageSetBinding
1953 {
1954 spv::ExecutionModel model;
1955 uint32_t desc_set;
1956 uint32_t binding;
1957
1958 inline bool operator==(const StageSetBinding &other) const
1959 {
1960 return model == other.model && desc_set == other.desc_set && binding == other.binding;
1961 }
1962 };
1963
1964 struct InternalHasher
1965 {
1966 inline size_t operator()(const SetBindingPair &value) const
1967 {
1968 // Quality of hash doesn't really matter here.
1969 auto hash_set = std::hash<uint32_t>()(value.desc_set);
1970 auto hash_binding = std::hash<uint32_t>()(value.binding);
1971 return (hash_set * 0x10001b31) ^ hash_binding;
1972 }
1973
1974 inline size_t operator()(const LocationComponentPair &value) const
1975 {
1976 // Quality of hash doesn't really matter here.
1977 auto hash_set = std::hash<uint32_t>()(value.location);
1978 auto hash_binding = std::hash<uint32_t>()(value.component);
1979 return (hash_set * 0x10001b31) ^ hash_binding;
1980 }
1981
1982 inline size_t operator()(const StageSetBinding &value) const
1983 {
1984 // Quality of hash doesn't really matter here.
1985 auto hash_model = std::hash<uint32_t>()(value.model);
1986 auto hash_set = std::hash<uint32_t>()(value.desc_set);
1987 auto tmp_hash = (hash_model * 0x10001b31) ^ hash_set;
1988 return (tmp_hash * 0x10001b31) ^ value.binding;
1989 }
1990 };
1991
1992 // Special constant used in a {MSL,HLSL}ResourceBinding desc_set
1993 // element to indicate the bindings for the push constants.
1994 static const uint32_t ResourceBindingPushConstantDescriptorSet = ~(0u);
1995
1996 // Special constant used in a {MSL,HLSL}ResourceBinding binding
1997 // element to indicate the bindings for the push constants.
1998 static const uint32_t ResourceBindingPushConstantBinding = 0;
1999 } // namespace SPIRV_CROSS_NAMESPACE
2000
2001 namespace std
2002 {
2003 template <SPIRV_CROSS_NAMESPACE::Types type>
2004 struct hash<SPIRV_CROSS_NAMESPACE::TypedID<type>>
2005 {
2006 size_t operator()(const SPIRV_CROSS_NAMESPACE::TypedID<type> &value) const
2007 {
2008 return std::hash<uint32_t>()(value);
2009 }
2010 };
2011 } // namespace std
2012
2013 #endif